Android - SQL syntax error
Here is my code, with unrelated stuff removed:
public class DataManager extends SQLiteOpenHelper
{
private final static String DB_TABLE = "Nums";
private ContentValues initialValues;
private static SQLiteDatabase myDB;
public DataManager()
{
initialValues = new ContentValues();
if(null != myDB)
{myDB.close();}
myDB = getWritableDatabase(); // This causes NullPointerException which is next on my TODO list
}
public void addValues(String num, String val)
{
开发者_运维知识库 initialValues.clear();
initialValues.put(num,val);
myDB.insert(DB_TABLE, null, initialValues); // THIS LINE CAUSES ERROR
}
}
I can CREATE
the database but I can't INSERT
without getting this error:
android.database.sqlite.SQLiteException: near "1": syntax error: , while compiling: INSERT INTO Nums(1) VALUES(?);
The database table Nums
looks like this:
Num | Val
=========
1 | 23
2 | 34
3 | 6
4 | 3
5 | 5
6 | 56
7 | 34
8 | 45
9 | 32
10 | 23
As you can see, I'm trying to create a database with a list of numbers from 1 -> n where each number has a value beside it. All values in the database are String
. There was a reason I didnt choose INT
but cant remember now.... :(
Can anyone see where my syntax is wrong? My phone is rooted so I can use an SQLite Browse app to view the database, and the table is created, its just empty!
Thanks.
The syntax for put is ContentValues.put(columnName, value). Try the following code.
public void addValues(String num, String val)
{
initialValues.clear();
initialValues.put("Num",num);
initialValues.put("Val",val);
myDB.insert(DB_TABLE, null, initialValues);
}
Just as some helpful suggestions, you don't need to save a reference to myDb. You can just always call getWritableDatabase() inside of your SqlLiteOpenHelper.
精彩评论