Search code examples
javaandroidstringsqliteandroid-sqlite

is there any advantage of using SQLitestatement bindstring method instead of simple string concatenation for executing sql statements


I wanted to insert values in a table in an SQLite Database in Android Studio.I wanted to ask which method should I prefer from the given two methods below. I learned the first method from a course,but I want to use the second method.That's why I am asking the question

articleId,articleContent and articleTitle are all of type string.

Please specify the pros and cons of each method if you can.You may suggest another method if you want to.

String sql = "INSERT INTO articles (articleId, title, content) VALUES (?, ?, ?)";
SQLiteStatement statement = articlesDB.compileStatement(sql);
statement.bindString(1, articleId);
statement.bindString(2, articleTitle);
statement.bindString(3, articleContent);
statement.execute();

OR simply using string concatenation:

sqliteDatabase.execSQL("INSERT INTO articles (articleId, title, content) VALUES (" + articleId + ", " + articleTitle + ", " + articleContent + ")");

Solution

  • Yes, it is always recommended to use bindString() to avoid possible attacks in your database through SQL Injection.

    In your particular case, it seems that, the values to be inserted are from your code only, not from any dynamic input source - e.g. user input. In that case, it could be safe to use any of the methods you mentioned in your question.

    In your case, in stead of string concatenation, you may also use insert() from SQLiteDatabase class, which is safe from any syntax error:

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put("articleId", articleId);
    values.put("title", articleTitle);
    values.put("content", articleContent);
    db.insert("articles", null, values);
    

    It returns the row ID of the newly inserted row, or -1 if an error occurred.

    However, if you are taking the values from user input, then using string concatenation makes your database completely vulnerable to potential attackers. That's why it is always recommended to use bindString() method of SQLiteProgram class to execute sql where we need to pass values.

    Another reason is, bindString() can invoke java.lang.IllegalArgumentException. So, using this method can be helpful for exception handling and debugging purpose in case any syntax error occurs.