I am getting syntax error when trying to insert data into my database when it is created.
I am using the following code:
//DatabaseHelper class
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_INSPECTION_TABLE);
db.execSQL(CREATE_AREA_TABLE);
db.execSQL(CREATE_RUN_TABLE);
db.execSQL(CREATE_LOCATION_TABLE);
db.execSQL(CREATE_INSPECTORS_TABLE);
db.execSQL(CREATE_ISSUE_LOCATION_TABLE);
db.execSQL(CREATE_ISSUE_TYPE_TABLE);
db.execSQL(CREATE_RACKING_SYSTEM_TABLE);
db.execSQL(CREATE_COMPONENT_TABLE);
db.execSQL(CREATE_RISK_TABLE);
db.execSQL(CREATE_ACTION_TABLE);
db.execSQL(CREATE_MANUFACTURER_TABLE);
db.rawQuery("INSERT INTO " + INSPECTORS_TABLE + "(" + INSPECTOR_NAME + ") " +
"SELECT 'Joe Bloggs' AS " + INSPECTOR_NAME +
" UNION SELECT 'John Major' " +
" UNION SELECT 'Dan the man'"
, null);
db.rawQuery("INSERT INTO " + ACTION_TABLE + "(" + ACTION_REQUIRED + ") " +
"SELECT 'Red Risk' AS " + ACTION_REQUIRED +
" UNION SELECT 'Amber Risk' " +
" UNION SELECT 'Green Risk'"
, null);
Edited again following RedFliter’s great advice. I’m sure the query is now right, but although I don’t get any errors no records get inputed into the tables (deleted the database each time using the DDMS).
Am I putting this code in the right place (i.e. onCreate)?
Not sure where I’m going wrong..
Many thanks.
You need to add single quotes around your strings:
This approach is subject to SQL injections. You will need to guard against this.
Update:
For multiple row inserts, you need to do: