Daniel Valencia
Daniel Valencia

Reputation: 697

Using quotes in SQLite an Android

I have a doubt about a code line in an android app with SQlite:

if(db != null)
    {
        db.delete("Users", null, null);

        //Insert 5 users
        for(int i=1; i<=5; i++)
        {
            //Generate the data
            int code = i;
            String name = "User" + i;

            //Insert data on table Users
            db.execSQL("INSERT INTO Users (code, name) " +
                       "VALUES (" + code + ", '" + name +"')");
        }
    }

All the code work perfectly, but in the line: db.execSQL("INSERT INTO Users (code, name) " + "VALUES (" + code + ", '" + name +"')"); if I delete the 'character, the app crashes. Can anyone tell me why I must to use the 'character and also the "? Why the " are not enough?

I'm a noob, sorry if my question is too basic.

Upvotes: 0

Views: 588

Answers (2)

Erik
Erik

Reputation: 1694

First, good lord, never write SQL like that. Do what the other answer(s) say to do inserts.

Second, it doesn't work because the name column is a string and so it needs to be quoted in an insert statement. The SQL that does the insert is:

INSERT INTO Users (code, name) VALUES (666, 'Bruce Dickinson')

Upvotes: 2

user155542
user155542

Reputation: 501

use a class ContentValues to set informations for compile an SQL Statement.

ex:

ContentValues content = new ContentValues();
content.putString("name", "Bruce Dickinson");
content.putInt("code", 666);

SqliteDatabase database = helper.getWritableDatabase();
database.insert("tablename", null, content);

Upvotes: 1

Related Questions