0

so I am trying to understand how prepared statements are handled exactly? I have this code but I am unsure if it is using prepared statement or how to add prepared statements to it.

Code:

/*
     * Creating a word
     */
    public long createword(DatabaseWords word) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_DICTIONARYID, word.get_dictionaryId());
        values.put(KEY_WORD1, word.get_word1());
        values.put(KEY_WORD2, word.get_word2());
        values.put(KEY_WORD3, word.get_word3());
        values.put(KEY_WORD4, word.get_word4());

        // insert row
        long word_id = db.insert(TABLE_WORDS, null, values);

        return word_id;

    }

How do I include prepared statements to A. make it go quicker, B. prevent attacks to the db

Lion789
  • 4,402
  • 12
  • 58
  • 96

1 Answers1

2

Yes, insert() uses prepared statements under the hood: sqlite_prepare_v2() to compile the SQL and then sqlite3_bind_*() to bind the arguments from ContentValues. This prevents the usual SQL injection attacks.

To use prepared statements for performance i.e. do the SQL compilation only once and reuse the same prepared statement for multiple queries with different bind args, see SQLiteDatabase.compileStatement() and SQLiteStatement.

laalto
  • 150,114
  • 66
  • 286
  • 303
  • Oh ok, so I do not need to do anything else? – Lion789 Feb 21 '14 at 15:53
  • Is it not essentially calling the same thing for multiple queries already (my code) with just the argument pertaining to each word? – Lion789 Feb 21 '14 at 15:58
  • No, currently each call to `insert()` prepares a new statement (essentially a program in sqlite "bytecode") and runs it with the given args. With `SQLiteStatement`s you can run the same program with different args - useful if you use the same kind of queries over and over again. – laalto Feb 21 '14 at 16:03
  • Anyway you can show me an example? – Lion789 Feb 21 '14 at 16:04
  • The duplicate linked by Artoo Detoo has a simple example. – laalto Feb 21 '14 at 16:06