How to create table using sqlite database in android?

拜拜、爱过 提交于 2019-12-11 13:57:40

问题


public class MyAct extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        SQLiteDatabase db = openOrCreateDatabase("MyDb",MODE_PRIVATE,null);
        db.execSQL("CREATE TABLE IF NOT EXISTS MyTab (Month INT(2),Date INT(2),Year INT(4),Event VARCHAR;");
        db.execSQL("INSERT INTO MyTab VALUES (0,1,2012,'mini_proj');");
        db.close();

    }
}

I have written this small snippet to create a table, but it's not working. What is the problem with this code?


回答1:


In your first query, you are missing a closing brace:

CREATE TABLE IF NOT EXISTS MyTab (
    Month INT(2),
    Date INT(2),
    Year INT(4),
    Event VARCHAR;

It should be:

CREATE TABLE IF NOT EXISTS MyTab (
    Month INT(2),
    Date INT(2),
    Year INT(4),
    Event VARCHAR
)

Also, note that the query doesn't need to end with a ;, as mentioned in the docs:

Parameters
sql the SQL statement to be executed. Multiple statements separated by semicolons are not supported.

Also, you should ALWAYS check your LogCat output, since this should throw a SQLiteException.


Some further SQLite notes:

  1. SQLite doesn't have a VARCHAR-type. It only has TEXT and will convert any text-like type into it.
  2. Note that giving a length for a datatype is also ignored by SQLite:

SQLite does not impose any length restrictions (other than the large global SQLITE_MAX_LENGTH limit) on the length of strings, BLOBs or numeric values.



来源:https://stackoverflow.com/questions/13893473/how-to-create-table-using-sqlite-database-in-android

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