尝试在创建数据库时将数据插入数据库时出现语法错误。
我使用以下代码:
//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);
按照RedFliter的建议再次编辑。我确定查询现在是正确的,但是虽然我没有收到任何错误,但没有记录被输入到表中(每次使用DDMS都删除了数据库)。
我是否将此代码放在正确的位置(即onCreate)?
不知道我哪里错了..
非常感谢。
答案 0 :(得分:3)
您需要在字符串周围添加单引号:
db.rawQuery("INSERT INTO " + INSPECTIONS_TABLE + " (" + INSPECTOR_NAME + ") VALUES " + "('Joe Blogs', 'John Smith', 'Franky Hollywood')", null);
此方法受SQL注入的影响。你需要防范这一点。
<强>更新强>
对于多行插入,您需要执行以下操作:
db.rawQuery("INSERT INTO " + INSPECTIONS_TABLE + "(" + INSPECTOR_NAME + ") " + "select 'Joe Bloggs' as " + INSPECTOR_NAME + " UNION ALL select 'John Major' UNION ALL select 'Dan the man'", null);
答案 1 :(得分:-1)
使用如下所示,您可以将日期无法插入数据库......
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(POST_ID,"Your ID here");
values.put(POSTER_ID,"Poster id " );
values.put(POSTER_NAME, msg.poster_name);
values.put(POSTER_IMAGE_PATH,msg.poster_image_path==null ||msg.poster_image_path.length()==0?"":msg.poster_image_path);
values.put(PLAYER_TYPE, msg.player_type);
values.put(POST_TEXT, msg.post_text);
db.insert(TABLE_NAME, null, values);
db.close();
答案 2 :(得分:-1)
只需将字符串值放入引号
即可db.rawQuery("INSERT INTO " +
INSPECTIONS_TABLE + "(" + INSPECTOR_NAME + ")
VALUES " + "('Joe Blogs', 'John Smith', 'Franky Hollywood')", null);