2014-09-21 146 views
0

我有两个表,通过下面的语句创建的:如何使用参数搜索数字?

create table maintable (_id integer primary key, name) 
    create table foreigntable (_id integer primary key, object, foreign key (object) references maintable(_id) 

我想查询foreigntablemaintable引用特定对象的所有项目。假设maintable中感兴趣的id存储在objectId中。

为什么下面的代码没有返回结果?

Cursor dataCursor = database.query("foreigntable", null, "object=?", new String[] { Long.toString(objectId)}, null, null, null); 

我得到下面的查询结果:

Cursor dataCursor = database.rawQuery("select * from foreigntable where object=" + objectId, null); 

什么也可以工作:

Cursor dataCursor = database.query("foreigntable", null, "object="+objectId, null, null, null, null); 

回答

1
"object=?", new String[] { Long.toString(objectId)} 

此代码对字符串的object列中的值进行比较。 这种比较总是会失败,因为数字不是字符串。

尽管使用参数通常是一个好主意,但Android的数据库API只允许使用字符串,并且当您有数字时,应将其直接插入到SQL查询字符串中。

+0

无赖,谢谢!就我个人而言,我不同意这种设计,但肯定有一个解释。 – nyi 2014-09-22 08:59:35