0

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

0

3 Answers 3

5

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 + "');");
Sign up to request clarification or add additional context in comments.

1 Comment

you are missing quotes around filename and newHash in the query
3

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.

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.