How can I create a new table in my SQLite Database using a param from a Java String variable?

Binyamin Robbins :

I am trying to create a new table in SQLite using a preexisting Java String variable but the variable name is not being recognized as Java... How can I fix this?

    String name1 = textViewPerson1.getText().toString();
    String name2 = textViewPerson2.getText().toString();
    String name3 = textViewPerson3.getText().toString();

    try{
        SQLiteDatabase database = this.openOrCreateDatabase("NewUsers",MODE_PRIVATE,null);
        database.execSQL("CREATE TABLE IF NOT EXISTS newUsers (name VARCHAR, hitCount INT(2))");
        database.execSQL("INSERT INTO newusers (name,age) VALUES (name1,17)");
        database.execSQL("INSERT INTO newusers (name,age) VALUES (name2, 16)");
    }catch (Exception e){
        e.printStackTrace();
    }

}
Alejandro Venegas :

I recommend to you use quotes in the sql sentences and specify the value for your varchar, like :

database.execSQL("CREATE TABLE IF NOT EXISTS 'newUsers' ('name' VARCHAR(25), 'hitCount' INT(2))");

And you should exit the "String" Context in the insert lines, something like this :

database.execSQL("INSERT INTO 'newusers' (name,age) VALUES ('"+name1+"',17)");

Obviously there exist more cleans options like StringBuilder, but this should help.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=20935&siteId=1