在數據庫中用string作為where條件查詢數據庫,程序就會關閉。如果換成數字作為條件,就沒問題。幫我看一下代碼:
public ArrayList<Contact> getAvailableList()
{
// TODO Auto-generated method stub
ArrayList<Contact> results = new ArrayList<Contact>();
String[] columns = new String[]{KEY_NAME, KEY_NUMBER, KEY_STATUS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=available" , null, null, null, KEY_NAME);
String sName = "";
String sNum = "";
String status = "";
int iName = c.getColumnIndex(KEY_NAME);
int iNumber = c.getColumnIndex(KEY_NUMBER);
int iStatus = c.getColumnIndex(KEY_STATUS);
Contact contact;
for(c.moveToFirst(); ! c.isAfterLast(); c.moveToNext())
{
contact = new Contact();
sName += c.getString(iName);
sNum += c.getString(iNumber);
status += c.getString(iStatus);
contact.setName(sName);
//contact.setPhoneNumber(sNum);
contact.setPhoneNumber("0".concat(sNum));
contact.setStatus(status);
results.add(contact);
sName = "";
sNum = "";
status = "";
}
return results;
}
在SQL中要把字符安用括號括起來的。像這樣:
// 添加這個 v v
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"='available'",
null, null, null, KEY_NAME);
如果你用動態數據,可以用selectionArgs
參數:
String status = "available";
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_STATUS +"=?",
new String[] {status}, null, null, KEY_NAME);
這個方法可以保護你不受SQL注入的影響。