如何在Android中使用SQLite数据库中创建表? [英] How to create table using sqlite database in android?
问题描述
公共类MyAct延伸活动{
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.main); SQLiteDatabase DB = openOrCreateDatabase(MYDB,MODE_PRIVATE,NULL);
db.execSQL(CREATE TABLE IF NOT EXISTS编辑MyTAB(月INT(2),日期INT(2),年INT(4),事件VARCHAR;);
db.execSQL(INSERT INTO编辑MyTAB VALUES(0,1,2012,'mini_proj'););
db.close(); }
}
我写了这个小片段来创建一个表,但它不工作。与此code中的问题是什么?
在第一个查询,你缺少一个右括号:
CREATE TABLE IF NOT EXISTS编辑MyTAB(
月INT(2),
日期INT(2),
年INT(4),
事件VARCHAR;
它应该是:
CREATE TABLE IF NOT EXISTS编辑MyTAB(
月INT(2),
日期INT(2),
年INT(4),
事件VARCHAR
)
另外,请注意查询并不需要以结束;
,如文档中提到:
参数结果
的 SQL 的要执行的SQL语句。 用分号分隔的多个语句不被支持。
块引用>此外,你应该始终检查LogCat中的输出,因为这应该抛出一个
SQLiteException
。一些进一步的SQLite的注意事项:
- SQLite没有一个
VARCHAR
型。它只有TEXT
并会转换任何文本样型进去。- 请注意,给一个数据类型的长度也由SQLite的忽略:
SQLite的不强加任何长度限制(比其他大
全球SQLITE_MAX_LENGTH
限制)对字符串,BLOB的长度或
数值。
块引用>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?
解决方案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 hasTEXT
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_LENGTH
limit) on the length of strings, BLOBs or numeric values.
这篇关于如何在Android中使用SQLite数据库中创建表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!