2016-09-10 59 views
-1

我是Android中SQLite的新手。我已经成功地创建了这个模式的数据库:如何在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"; 
    } 
} 

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

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

我已阅读the documentation,但我不知道哪里来输入“1993年”在查询方法。

回答

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(); 
+0

感谢。这工作,但它会工作,如果结果没有发现第一行? – X09

+0

是的,所以如果你有多个行与1993年的id,你将能够让所有的人都 –

+0

我编辑awnser,'urls'和'titles'现在将持有的每一行与1993年 –

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); 
相关问题