问题
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:
- SQLite doesn't have a
VARCHAR-type. It only has TEXT and will convert any text-like type into it. - 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_LENGTHlimit) on the length of strings, BLOBs or numeric values.
来源:https://stackoverflow.com/questions/13893473/how-to-create-table-using-sqlite-database-in-android