I have a problem with an SQL INSERT statement. I am trying to insert data stored in Strings but this always throws an error.
private final String HASH_DB = "hashDb";
private final String HASH_TABLE2 = "newHashes";
SQLiteDatabase hashDB = null;
hashDB = this.openOrCreateDatabase(HASH_DB, MODE_PRIVATE, null);
hashDB.execSQL("CREATE TABLE IF NOT EXISTS " + HASH_TABLE2
+ " (dialogID INT, Filename VARCHAR, Hash VARCHAR);");
hashDB.execSQL("INSERT INTO " + HASH_TABLE2 +" (dialogID, Filename, Hash) "
+ " Values (dialogID, filename, newHash);");开发者_运维百科
dialogID is an int, and Filename and Hash are both Strings, I have confirmed that the correct data is stored in these by displaying them in a Toast.
The above throws an error but if I change the last line to this below, i.e hardcoding the data to be inserted it works.
hashDB.execSQL("INSERT INTO " + HASH_TABLE2 +" (dialogID, Filename, Hash) "
+ " Values (4, 'filename', 'newHash');");
How can I get this working?
Many Thanks
Matt
I haven't really worked with Android, but are those files not files variables?
Shouldn't it be
hashDB.execSQL("INSERT INTO " + HASH_TABLE2 +" (dialogID, Filename, Hash) "
+ " Values (" + dialogID + ", '" + filename + "', '" + newHash + "');");
You need to close the string quotes and add your variables on your Insert statement. Something like this;
hashDB.execSQL("INSERT INTO " + HASH_TABLE2 +" (dialogID, Filename, Hash) "
+ " Values (" + dialogID + ", '" + filename + "', '" + newHash + "');");
Assuming you have the three variables (dialogID, filename and newHash) defined elsewhere.
You are passing wrong the parameters to the query.
You should do this in the following way:
" Values(" + dialogId +", " +filename +", " + newHash +");"
or you should use
public long insert (String table, String nullColumnHack, ContentValues values)
Example:
ContentValues values = new ContentValues();
values.put("dialogId", dialogId);
values.put("filename", filename);
values.put("newHash", newHash);
mDatabase.insert("your_table", null, values);
精彩评论