2012-10-16 397 views
3

我將數據保存在我的SQL數據庫中。將sqlite與字符串進行比較

現在我想比較這保存的數據,用繩子

事情是這樣的:

​​

現在我要檢查,如果「家」已經在數據庫,有若第

像這樣

if (example == [SQL Data]) { 
} 
else { 
} 

現在,我怎麼能做到這一點?

+0

你剛纔一列或多個列? –

+0

所以這看起來更像是一個sql問題。看看這些:http://stackoverflow.com/questions/3634984/insert-if-not-exists-else-update,http://stackoverflow.com/questions/418898/sqlite-upsert-not-insert-或替換 –

+0

從[SQLiteDatabase.html#query()]開始(http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#query(java.lang.String,%20java.lang .String [],%20java.lang.String,%20java.lang.String [],%20java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String))或其一個變體。 –

回答

1

寫偷了我回復Sharath的評論作爲回答,因爲代碼會混亂在評論中:

不說你的回覆是錯誤的,但是從表中選擇所有內容並在數據庫外迭代它並且不應該被建議作爲對這個問題的回答,因爲這樣做一般來說是一個不好的習慣。

我通常這樣做,如果我想查看數據庫中是否存在某條記錄,我喜歡這樣。不是要去爭辯使用做,而在正常while循環,因爲這是關於不同的偏好;)

String query = "SELECT * FROM table_name WHERE column_name=" + the_example_string_to_find;    
Cursor cursor = db.rawQuery(query, null); 

if(cursor.getCount() > 0) { 
    cursor.moveToFirst(); 
    while(!cursor.isAfterLast()) { 
     // Do whatever you like with the result. 
     cursor.moveToNext(); 
    } 
} 
+1

嗨,謝謝你的回答 可悲的是我在這裏得到一個nullpointerexception:光標cursor = db.rawQuery – user1750720

+0

問題是,我在一個broadcastreceiver – user1750720

+0

如何創建數據庫? – Darwind

0

您需要首先從數據庫中提取所有數據,然後使用從數據庫中獲取的數據檢查數據。

看一看鏈接sample database example

假設你從數據庫中有一個光標對象

cursor = db.rawQuery("SELECT yourColumnName FROM "+TABLE_NAME, null); 
if(!cursor.moveToFirst()){ 

} 
else{ 

do { 
if(cursor.getString(0).equals(example)) 
//do something which you want and break 
break; 
} while (cursor.moveToNext()); 

} 
+3

Performancewise您的方法是完全錯誤的。您的原始查詢應該如下所示:SELECT * FROM table_name WHERE row_name = the_example_string。 不要僅僅選擇數據庫中的所有內容,並在數據庫能夠更高效地進行比較時使用編程語言進行比較。 此外,Android SQLite數據庫類有一個名爲getCount()的方法,您可以在執行select時獲取返回的行數。 – Darwind

+0

是的你是對的,但他沒有提及他是否需要某些特定值的數據,以便我們可以使用where子句。 他的信息只是搜索字符串是否存在於數據庫中,或者我們需要從數據庫中獲取整個數據。我的方法錯了嗎?如果是的話,你可以建議任何其他方式請 –

7

這樣做

String sql = "SELECT * FROM your_table WHERE your_column = '" + example + "'"; 
Cursor data = database.rawQuery(sql, null); 

if (cursor.moveToFirst()) { 
// record exists 
} else { 
// record not found 
} 

here

0
// Getting Specific Record by name. 
// in DB handler class make this function call it by sending search criteria. 
    Records getRecord(String name) { 
     SQLiteDatabase db = this.getReadableDatabase(); 
     Cursor cursor = db.query(TABLE_NAME, new String[]{KEY_ID, KEY_NAME, KEY_Auth_Name, KEY_B_PRICE}, KEY_ID + "=?", 
       new String[]{name}, null, null, null,null); 
     if (cursor.getCount() > 0) 
      cursor.moveToFirst(); 
     Records Records = new Records(Integer.parseInt(cursor.getString(0)), 
       cursor.getString(1), cursor.getString(2),cursor.getString(3)); 
// return book 
     return Records; 
    }