Search code examples
androidsqliteandroid-sqlitesqliteopenhelper

SQLiteDatabase.execSQL(query) - Multiple SQL commands inside the onCreate() method not working


I am new to android. I haven't worked with SQLite DBs before.
I think this is a very basic question, but I am unable to find the solution.

The code is here (assume declarations)

public void onCreate(SQLiteDatabase db) {

    String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + FORMULA + "("
            + CAT_CD + " TEXT ," + S_CAT_CD + " TEXT, PRIMARY 
 KEY(CAT_CD,S_CAT_CD))";
    db.execSQL(CREATE_CATEGORIES_TABLE);

    String CREATE_CAT_DESC_TABLE="CREATE TABLE "+ FORMULA_CAT_DESC + "
("+CAT_CD+" TEXT PRIMARY KEY, "+ DESC +" TEXT ) ";
    db.execSQL(CREATE_CAT_DESC_TABLE);

    String CREATE_CURRENCY_TABLE="CREATE TABLE "+ VI_CURRENCY + "("+ 
CURRENCY_CD +" TEXT PRIMARY KEY, "+ CURRENCY_SIGN +" TEXT ) ";
    db.execSQL(CREATE_CURRENCY_TABLE);

   String query=  "INSERT INTO "+ VI_CURRENCY +" ("+CURRENCY_CD +", 
"+CURRENCY_SIGN+ ") VALUES " +
            "('INR', '₹'), " +
            " ('USD','$') " +
            "('JPY','¥') ";
    db.execSQL(query);
 }

The first three commands execute successfully, while by executing the insert command, SQLite throws an exeption.


Solution

  • You could create a sql statement for each record

    String query1 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('INR', '₹')" ;
    
    String query2 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('USD','$')" ;
    
    String query3 =  "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " + "('JPY','¥')" ;
    
    db.execSQL(query1);
    db.execSQL(query2);
    db.execSQL(query3);
    

    Or insert multiple values in one statement, with the correct sintax it would be like this:

    String query = "INSERT INTO " + VI_CURRENCY + " (" + CURRENCY_CD + ", " + CURRENCY_SIGN + ") VALUES " +
                 "('INR', '₹'), " +
                 "('USD','$'), " +
                 "('JPY','¥')";
    db.execSQL(query);
    

    For more information visit SqlLite