简体   繁体   中英

Android SQL INSERT statement using variables problem

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, ie 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM