SQLite syntax error near “CREATE TABLE”

放肆的年华 提交于 2019-12-02 02:45:00

问题


Here's my code:

    String CREATE_DATABASE = "CREATE TABLE " + TABLE_NAME + "("  + 
            KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + 
            "title TEXT, "+
            "author TEXT, "+
            "state TEXT);";

    db.execSQL(CREATE_DATABASE);

The LogCat says : 12-11 23:43:50.553: E/AndroidRuntime(3706): android.database.sqlite.SQLiteException: near "CREATE TABLE": syntax error (code 1): , while compiling: CREATE TABLE PapersTable(_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, author TEXT, state TEXT);


回答1:


The CREATE TABLE syntax is all right as you've posted it.

I suspect there's a non-breaking space (ASCII 0xA0) between CREATE and TABLE. Replace it with the regular space (ASCII 0x20). That would explain the syntax error you posted: parser is treating CREATE TABLE as a single unknown token and not as two separate known tokens CREATE and TABLE.

What is definitely wrong is that you call db.close() on the SQLiteDatabase db passed in as a parameter to your function. You should only close databases you opened yourself and closing it this way will lead to an exception, albeit a different one.




回答2:


Try this code in your onCreate method.

  1. Remove AUTOINCREMENT for KEY_ID as it is already declared as Primary KEY.
  2. Remove ";" you placed just after the last bracket in string i.e. second last semicolon in string CREATE_DATABASE.
  3. Remove db.close() from oncreate()

Code To Replace: String CREATE_DATABASE = "CREATE TABLE "+TABLE_NAME+ " ( "+KEY_ID+" INTEGER PRIMARY KEY, "+KEY_TITLE+"TEXT, "+KEY_AUTHOR+"TEXT, "+KEY_STATE+"TEXT )"; db.execSQL(CREATE_DATABASE);




回答3:


In SQLite, a column declared integer primary key will auto increment, so try removing that:

String CREATE_DATABASE = "CREATE TABLE " + TABLE_NAME + "("  + 
        KEY_ID + " INTEGER PRIMARY KEY, " + 
        "title TEXT, "+
        "author TEXT, "+
        "state TEXT);";

See this answer for reference.



来源:https://stackoverflow.com/questions/20532339/sqlite-syntax-error-near-create-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!