2011-12-31 106 views
0

我写了下面的数据库查询。 但是,当我访问显示结果的列表活动时,应用程序崩溃。为什么我的查询崩溃了?

我跟踪误差低于(其他简单的查询方式工作得很好)的方法:

public Cursor fetchInterface_HSE_Entries(String string) throws SQLException{ 
    String[] columns = new String[] {KEY_ROW_ID_INTERFACE, KEY_TEXTVIEW_VALUE, KEY_CATEGORY_OPTIONS, KEY_WORKSCREEN}; 
    String whereClause = KEY_WORKSCREEN+"=" + string; 
    Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause, null, null, null, null); 

    if(cursor != null){ 
     cursor.moveToFirst(); 
    } 
    return cursor; 
} 

这是我的错误日志的一部分:

12-31 16:13:38.851: E/AndroidRuntime(480): Caused by: android.database.sqlite.SQLiteException: no such column: testInterface1: , while compiling: SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1 

回答

1

与尝试:

String whereClause = KEY_WORKSCREEN+"='" + string + "'"; 

您需要在查询中引用文本值,否则它们将被解释为列名(或fu节点,或其他)。

请注意,这对于SQL注入攻击是不安全的,您应该使用绑定变量。

String whereClause = KEY_WORKSCREEN+" = ?"; 
Cursor cursor = db.query(TEXTVIEWS_TABLE, columns, whereClause, 
         new String[]{string}, null, null, null); 
+0

感谢您警告我关于我的安全问题,我会研究它们,我非常喜欢Android,特别是使用数据库,但尽我所能学习 – Eugen 2011-12-31 14:33:16

+0

Humm ...有人downvoted这,不知道为什么。也许有一个错字或我错过了什么?尤金,如果你尝试其中任何一个,请报告,如果工作或不,所以我可以更正(或删除)这个答案? – Mat 2011-12-31 14:39:35

+0

是的,你的代码工作得很好。非常感谢你的输入, – Eugen 2011-12-31 14:43:57

1

因为你不把引号放在whereClause的周围。 尝试:

String whereClause = KEY_WORKSCREEN+"='" + string + "'"; 

你可以清楚地看到你的错误日志:

SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1 

应该是:

SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen='testInterface1' 
1
SELECT _id, textviewvalue, categoryoptions, workscreen FROM interfacetable WHERE workscreen=testInterface1 

由于错误说你没有testInterface1 collumn做在接口表中,我认为你的sql语句中应该有值而不是testInterface1。在db中运行你的查询,你会看到相同的错误。

1

您需要将where子句中的字符串值放入引号中。

1

Workscren是字符串编辑您的查询并添加单引号。 Key-workscreen +“=”'+ string +'“就像那样