gpt4 book ai didi

java - SQL查询Android Where子句的问题

转载 作者:IT王子 更新时间:2023-10-29 06:25:17 25 4
gpt4 key购买 nike

我有以下创建表格的代码。我将数据插入其中,看起来像这样

_id     date     recordName     total
--------------------------------------
7 2011 TestMaxRecord 5

Java代码:

public static final String KEY_ROWID = "_id";   
public static final String KEY_DATE = "date";
public static final String KEY_TOTAL = "total";
public static final String KEY_RECORD_NAME = "recordName";

private static final String DATABASE_CREATE_RECORDS = "create table " + DATABASE_TABLE_RECORDS + " ("
+ KEY_ROWID + " integer primary key autoincrement, "
+ KEY_DATE + " text not null, "
+ KEY_RECORD_NAME + " text not null, "
+ KEY_TOTAL + " text not null);";

public Cursor getRecord(String name) throws SQLException {
return mDb.query(true, DATABASE_TABLE_RECORDS, new String[] {KEY_ROWID, KEY_DATE, KEY_RECORD_NAME, KEY_TOTAL}, KEY_RECORD_NAME + " = " + name, null, null, null, null, null);
}

每次 where name = "TestMaxRecord"(尽管那里有数据)都会抛出异常,并出现以下错误

android.database.sqlite.SQLiteException: no such column: TestMaxRecord: , while compiling: SELECT DISTINCT _id, date, recordName, total FROM Records WHERE recordName=TestMaxRecord

在我看来,它正在寻找列标题 TestMaxRecord。我是一个 android 新手,但几乎完全从一个示例中复制了这部分(尽管它使用的是 int)。在查询中使用 int 和 Strings 之间有区别吗?

最佳答案

您需要在值周围加上单引号,否则它会将其视为一列。

KEY_RECORD_NAME + " = '" + name + "'"

注意:此解决方案对 Sql 注入(inject)开放,您应该使用参数占位符,并通过 selectionArgs 参数传递值:

public Cursor getRecord(String name) throws SQLException {
return mDb.query(true,
DATABASE_TABLE_RECORDS,
new String[] {KEY_ROWID, KEY_DATE, KEY_RECORD_NAME, KEY_TOTAL},
KEY_RECORD_NAME + " = ?",
new String[] {name},
null, null, null, null);
}

或者,查看 SQLiteQueryBuilder

关于java - SQL查询Android Where子句的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6564215/

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