2017-02-17 24 views
0

如何检查sqlite数据库如果行存在?我实施的SQLite数据库的风格就是这样检查行是否存在与这种实施sqlite db

public class EmployeeDBController extends SQLiteOpenHelper { 

    public EmployeeDBController(Context applicationcontext) { 
     super(applicationcontext, "registeruser.db", null, 1); 

    } 

    public SQLiteDatabase db; 
    //Creates Table 
    @Override 
    public void onCreate(SQLiteDatabase database) { 
     String query; 
     query = "CREATE TABLE register (userId INTEGER PRIMARY KEY, Name text, Age text, Gender text," + 
       "HomeAddress text, Password text, QRID text, udpateStatus TEXT)"; 
     database.execSQL(query); 
    } 
    @Override 
    public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) { 
     String query; 
     query = "DROP TABLE IF EXISTS register"; 
     database.execSQL(query); 
     onCreate(database); 
    } 
} 

例如:我想检查是否有“名”的sqlite的分贝为“约翰”。

+0

是的,我已经做到了,对不起我的问题是不明确的,我有SELECT * FROM [表] WHERE [列名] = [某事],但我不知道接下来要做什么,因为有很多格式。我应该做光标来获得它的价值吗? @MarkKeen –

+0

@johnedgarotom使用你的声明和我的回答 –

+0

@MarkKeen是的,它会工作,但你能告诉我们为什么你不喜欢原始查询吗? –

回答

0

使用此方法!

public boolean isRowExist(/*YOUR_INPUTS*/){ 
    try { 
     db = mDBHelper.getReadableDatabase(); 
     String selectQuery = YOUR_SEARCH_QUERY_STATMENT 
     //You should use YOUR_INPUTS to create a selectQuery that can select the row/rows for you 

     Cursor c = db.rawQuery(selectQuery, null); 
     if(c.getCount()>=1){ 
      c.close(); 
      return true; 
     } 
     c.close(); 
     return false; 
    } catch (Exception e) { 
     return false; 
    } 
} 
+0

谢谢先生@AtefHares,我会尽力的 –

1

有一个helper function,以避免渣土周围的光标:

public boolean rowExists(String table, String column, String value) { 
    long count = DatabaseUtils.queryNumEntries(db, 
      table, column+" = ?", new String[]{ value }); 
    return count > 0; 
}