0

我正在尝试学习如何在 Android 中使用数据库,到目前为止,我已经学会了如何获取表中的所有数据行,但我不确定如何使用 SQL 查询来搜索值等于我传递给下面方法的字符串值?

我想知道是否有人可以添加一些简单的代码,如何在我的代码中使用 SQL 查询数据库?感谢帮助!谢谢!

像这样的东西:String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH = filePath";

// Read from database
public String readContacts(String filePath){

    String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME, TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};
    Cursor c = db.query(DB_TABLE, columns, null, null, null, null, null);

    int id = c.getColumnIndex(TABLE_ID);
    int imagePath = c.getColumnIndex(TABLE_IMAGE_PATH);
    int name = c.getColumnIndex(TABLE_CONTACT_NAME);
    int number = c.getColumnIndex(TABLE_CONTACT_NUMBER);
    int address = c.getColumnIndex(TABLE_CONTACT_ADDRESS);

    String result = "";

    for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){ 
    result = result + c.getString(id) + " " + c.getString(imagePath) + " " + c.getString(name) + " " + c.getString(number) + " " + c.getString(address);
    }

    return result;
}
4

2 回答 2

3

你可以搜索查询

它的确切字符串

String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH  like  '"+filePath+"';

如果值包含您的字符串

String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH  like  '%"+filePath+"%';

如果价值需要从最后

String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH  like  '%"+filePath+"';

如果价值需要从一开始

String query = "Select * from DB_TABLE where TABLE_IMAGE_PATH  like  '"+filePath+"%';

把这些

SQLiteDatabase dbR = this.getReadableDatabase();
    Cursor cur = dbR.rawQuery("query", null);
            return cur

使用此光标,您可以获得价值。

于 2013-03-03T10:42:36.613 回答
1

您可以通过将查询代码修改为:

        String[] columns = new String[]{TABLE_ID, TABLE_IMAGE_PATH, TABLE_CONTACT_NAME,   TABLE_CONTACT_NUMBER, TABLE_CONTACT_ADDRESS};

        Cursor cursor = db.query(ANSWERS_TABLE,
            columns,
            columns[1] + " = ?", new String[]{filePath}, null, null, null);

看看这里:SQLiteDataBase 查询

于 2013-03-03T10:36:24.290 回答