从数组中获取数据库中的特定值

问题描述:

我试图从数组中的数据库中获取值或数据。从数组中获取数据库中的特定值

public Cursor checkExistence(){ 
     Cursor c=null; 
     String[] values={"headache","cold"}; 
     SQLiteDatabase db= getReadableDatabase(); 
     String query="SELECT * FROM "+TABLE_SYMPTOMS+" WHERE "+COLUMN_SYMP+" IN ("+toArrayRep(values)+")"; 
     c=db.rawQuery(query,null); 
     Log.i("From Cursor","Cursor Count : " + c.getCount()); 
     if(c.getCount()>0){ 
      String val= c.getString() 
      Log.i("From Cursor","No insertion"); 
     }else{ 
      Log.i("From Cursor","Insertion"); 
     } 
     db.close(); 
     return c; 
    } 



public static String toArrayRep(String[] in) { 
    StringBuilder result = new StringBuilder(); 
    for (int i = 0; i < in.length; i++) { 
     if (i != 0) { 
      result.append(","); 
     } 
     result.append("'" + in[i] + "'"); 
    } 
    return result.toString(); 
} 

String values={"headache","cold"}中,头痛存在但数据库中不存在冷。从上面的代码,光标返回Count=1这是count>0,因此我不能插入到table.I想知道我可以独立检查是否存在单个数据,并且不存在的将插入到表中因此,在这种情况下,“冷”将能够插入到表格中。

+0

对于你的逻辑,'c.getCount()== values.length' - >所有记录在数据库中。如果c.getCount()小于values.length,那么一些记录不在db中。虽然,没有逻辑,你可以做唯一插入1 sql:http://stackoverflow.com/questions/2779823/sqlite-query-to-insert-a-record-if-not-exists – Emma

如果您使用单个查询来检查所有值,那么您得到的是现有值的列表,并且您仍然必须在原始列表中搜索任何差异。

这是简单检查每个单独的值:

String[] values = { "headache", "cold" }; 
SQLiteDatabase db = getReadableDatabase(); 

db.beginTransaction(); 
try { 
    for (String value : values) { 
     long count = DatabaseUtils.queryNumEntries(db, 
       TABLE_SYMPTOMS, COLUMN_SYMP+" = ?", new String[] { value }); 
     if (count == 0) { 
      ContentValues cv = new ContentValues(); 
      cv.put(COLUMN_SYMP, value); 
      db.insert(TABLE_SYMPTOMS, null, cv); 
     } 
    } 
    db.setTransactionSuccessful(); 
} finally { 
    db.endTransaction(); 
} 
+0

感谢@CL,它的工作 – mcprilla79

您需要检查光标。 moveToFirst()在光标

  • =有记录。
  • 错误 =没有记录。

示例我的代码:

return database.query(table.getNameTable(), 
         table.getColumns(), 
         table.getWhereSelectTableScript(), 
         null, 
         table.getGroupBySelectTableScript(), 
         table.getHavingSelectTableScript(), 
         table.getOrderBySelectTableScript(), 
         table.getLimitRecordsSelectTableScript()); 

查看更多here

+0

抱歉,但不会帮助,我想通过'count = 0'得到值,它显示它不在数据库中的值。感谢您的帮助,虽然 – mcprilla79