如何检查我的 sqlite 表中是否有数据? [英] How can i check to see if my sqlite table has data in it?
问题描述
编辑,根据以下答案稍微更改了代码,但仍然无法正常工作.我还添加了一条日志消息,告诉我 getCount 是否返回 > 0,而且确实如此,所以我怀疑我的查询可能有问题?或者我对光标的使用..
我创建了一个表,我想检查它是否为空,如果它为空我想运行一些插入语句(存储在数组中).
I've created a table, and i want to check if its empty or not, if it's empty i want to run some insert statements (that are stored in an array).
下面是我的代码,虽然我没有错误,但当我拉出 .db 文件时,我可以看到它不起作用.你会如何解决这个问题?
Below is my code, while i have no errors, when i pull the .db file out i can see that it doesn't work. How would you approach this problem?
public void onCreate(SQLiteDatabase db) {
Log.i("DB onCreate", "Creating the database...");//log message
db.execSQL(createCATBUDTAB);
db.execSQL(createTWOWEETAB);
try{
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM CAT_BUD_TAB", null);
if (cur.getCount() > 0){
Log.i("DB getCount", " getcount greater than 0");//log message
//do nothing everything's as it should be
}
else{//put in these insert statements contained in the array
Log.i("DB getCount", " getcount less than 0, should read array");//log message
for(int i=0; i<13; i++){
db.execSQL(catInsertArray[i]);
}
}
}catch(SQLiteException e){System.err.println("Exception @ rawQuery: " + e.getMessage());}
}
对不起,如果这是一个非常愚蠢的问题或方法,我是这一切的新手.非常感谢任何答案!
Sorry if this is a pretty stupid question or approach, i'm new to all this. Any answers much appreciated!
推荐答案
对现有表的查询 SELECT COUNT(*)
应该从不返回 null.如果表中没有行,它应该返回包含值零的一行.
The query SELECT COUNT(*)
on an existing table should never return null. If there are no rows in the table, it should return one row containing the value zero.
相反,具有非零值的行表示它非空.
Conversely, a row with a non-zero value indicates that it's not empty.
在这两种情况下,都应该返回一行,这意味着它将始终通过
In both cases, one row should be returned, meaning that it will always go through the
//do nothing everything's as it should be
部分.
要修复它,请保持查询原样(您不想执行 select column_name
仅仅因为那是不必要的,并且可能有点低效).将其保留为 select count(*)
,它将始终返回一行,并使用以下代码(仅在我的脑海中测试过,所以要小心):
To fix it, leave your query as-is (you don't want to do select column_name
simply because that would be unnecessary and possibly a little inefficient). Leave it as select count(*)
, which will always return one row, and use the following code (tested only in my head so be careful):
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM CAT_BUD_TAB", null);
if (cur != null) {
cur.moveToFirst(); // Always one row returned.
if (cur.getInt (0) == 0) { // Zero count means empty table.
for (int i = 0; i < 13; i++) {
db.execSQL (catInsertArray[i]);
}
}
}
这篇关于如何检查我的 sqlite 表中是否有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!