gpt4 book ai didi

android - 计算数据库中特定记录的数量时出错

转载 作者:行者123 更新时间:2023-11-30 05:02:18 24 4
gpt4 key购买 nike

如何创建一个查询来计算数据库中特定记录的数量。我试过这段代码:

 public int getContactsCount(String name) {
String countQuery = "SELECT count(*) FROM database_names where _name ="+name;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
return cursor.getCount();


}

但是没有用。它说:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 26655
android.database.sqlite.SQLiteException: incomplete input (Sqlite code 1 SQLITE_ERROR): , while compiling: SELECT count(*) FROM database_names where _name =, (OS error - 2:No such file or directory)
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:948)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:559)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:603)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:63)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1493)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1427)
at com.example.myapplication.database_names.getContactsCount(database_names.java:68)
at com.example.myapplication.HazineHaActivity$1.onClick(HazineHaActivity.java:62)
at android.view.View.performClick(View.java:6663)
at android.view.View.performClickInternal(View.java:6635)
at android.view.View.access$3100(View.java:794)
at android.view.View$PerformClick.run(View.java:26199)
at android.os.Handler.handleCallback(Handler.java:907)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:216)
at android.app.ActivityThread.main(ActivityThread.java:7625)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

我该怎么做?

最佳答案

可能您的问题是您没有将参数 name 括在单引号中。
但正确的做法是在查询中使用占位符并传递 name 作为参数:

Cursor c = db.rawQuery(
"SELECT COUNT(*) AS counter FROM MY TABLE WHERE _NAME = ?",
new String[] {name}
);

db 替换为您的 SQLiteOpenHelper 对象。

关于android - 计算数据库中特定记录的数量时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58048591/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com