搜索数据库中的条目时出现语法错误

时间:2012-04-16 21:52:06

标签: java android database eclipse sqlite

当我尝试使用“洗衣机”作为搜索字符串搜索我的数据库中的特定条目以尝试查找“洗衣机”的数据库条目时,会出现错误:

04-16 21:43:28.951: E/AndroidRuntime(545): FATAL EXCEPTION: main
04-16 21:43:28.951: E/AndroidRuntime(545): java.lang.RuntimeException: Unable to start   activity  ComponentInfo{com.lukeorpin.theappliancekeeper/com.lukeorpin.theappliancekeeper.EntryStatis tics}: android.database.sqlite.SQLiteException: near "Machine": syntax error: , while compiling: SELECT _id, appliance_name, appliance_wattage, energy_rates FROM ApplianceDetails WHERE appliance_name=Washing Machine

,更具体地说:

at com.lukeorpin.theappliancekeeper.Database.getWattage(Database.java:122)
04-16 21:43:28.951: E/AndroidRuntime(545):  at com.lukeorpin.theappliancekeeper.EntryStatistics.onCreate(EntryStatistics.java:47)

以下是数据库搜索查询的代码:

public String getWattage(String spinnerChoice) {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
    if (c != null){
        c.moveToFirst();
        String wattage = c.getString(2);
        return wattage;
    }
    return null;
}

public String getEnergyRate(String spinnerChoice) {
    // TODO Auto-generated method stub
    String[] columns = new String[] { KEY_ROWID, KEY_NAME, KEY_WATTAGE, KEY_ENERGY};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);
    if (c != null){
        c.moveToFirst();
        String energyRate = c.getString(3);
        return energyRate;
    }
    return null;
}

这是创建方法的原始类:

final String spinnerChoice = getIntent().getStringExtra("Name");
    if(spinnerChoice==null){ 
        return;
    } 

Database data = new Database(this);
    data.open();
    String returnedWattage = data.getWattage(spinnerChoice); 
    String returnedEnergyRate = data.getEnergyRate(spinnerChoice);
    data.close();

有没有人知道为什么会出现此错误消息?感谢

编辑:这是错误指向的代码行(第122行):

Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "=" + spinnerChoice, null, null, null, null);

2 个答案:

答案 0 :(得分:1)

鉴于错误消息,您似乎没有引号表示appliance_name值比较的字符串。它应该是

WHERE appliance_name = 'Washing Machine'

我不熟悉api,但您可以尝试将第122行更改为

Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_NAME + "='" + spinnerChoice + "'", null, null, null, null);

答案 1 :(得分:1)

您需要将搜索字符串括在单引号中(在SQL查询中)。