如何在SQLite数据库中搜索字符串

时间:2016-09-10 16:20:08

标签: android sqlite

我是Android中的SQLite新手。我已使用此架构成功创建了数据库:

public final class BookDbSchema {

    private BookDbSchema() {
    }

    public static final class BookEntry implements BaseColumns{
        public static final String NAME = "bookItems";

        public static final String ID = "id";
        public static final String URL = "url";
        public static final String TITLE = "title";
    }
}

我遇到的问题是在数据库中搜索特定的字符串。

如果 1993 存在,我想搜索 id 列。请问我该怎么做?

我已阅读the documentation但我不知道在哪里输入" 1993"用于查询方法。

2 个答案:

答案 0 :(得分:1)

您可以使用以下方法:

Cursor query (String table, 
                String[] columns, 
                String selection, 
                String[] selectionArgs, 
                String groupBy, 
                String having, 
                String orderBy, 
                String limit)

query(NAME, new String[]{ID, URL, TITLE}, ID + "=?", new String[]{"1993"}, null, null, null, null);

答案 1 :(得分:1)

我相信你正在寻找这个

 Context context;
    BookDbSchema mDbHelper;

    public BookDbSchema (Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }
    ...

    ArrayList<String> urls = new ArrayList<>();
    ArrayList<String> titles = new ArrayList<>();
    ArrayList<String> ids= new ArrayList<>();

    mDbHelper = new BookDbSchema(context);
    SQLiteDatabase db = mDbHelper.getReadableDatabase();

    String[] projection = {
            FeedEntry.ID,
            FeedEntry.URL,
            FeedEntry.TITLE
    };

    String selection = FeedEntry.ID + " LIKE ? "; //WHERE
    String[] selectionArgs = {"1993"};   //VALUE

    Cursor c = db.query(
            FeedEntry.NAME,  // Your Table Name
            projection,
            selection,
            selectionArgs,
            null,
            null,
            null
    );


    if(c.getCount() != 0) {
        c.moveToFirst();
        for(int i = 0; i<c.getCount(); i++) {
            urls.add(c.getString(c.getColumnIndex(FeedEntry.URL)));
            titles.add(c.getString(c.getColumnIndex(FeedEntry.TITLE)));
            ids.add(c.getString(c.getColumnIndex(FeedEntry.ID)));
            c.moveToNext();
        }

        String firstUrl = urls.get(0);   //Returns the first url found
        String firstID = ids.get(0);   //Returns the first id found
        int urlSize = urls.size(); // returns the count of urls found
    }else{
        //Nothing found
    }


    c.close();
    db.close();