How do I use prepared statements in SQlite in Android?

前端 未结 5 574
無奈伤痛
無奈伤痛 2020-11-22 04:17

How do I use prepared statements in SQlite in Android?

5条回答
  •  一向
    一向 (楼主)
    2020-11-22 05:11

    If you want a cursor on return, then you might consider something like this:

    SQLiteDatabase db = dbHelper.getWritableDatabase();
    
    public Cursor fetchByCountryCode(String strCountryCode)
    {
        /**
         * SELECT * FROM Country
         *      WHERE code = US
         */
        return cursor = db.query(true, 
            "Country",                        /**< Table name. */
            null,                             /**< All the fields that you want the 
                                                    cursor to contain; null means all.*/
            "code=?",                         /**< WHERE statement without the WHERE clause. */
            new String[] { strCountryCode },    /**< Selection arguments. */
            null, null, null, null);
    }
    
    /** Fill a cursor with the results. */
    Cursor c = fetchByCountryCode("US");
    
    /** Retrieve data from the fields. */
    String strCountryCode = c.getString(cursor.getColumnIndex("code"));
    
    /** Assuming that you have a field/column with the name "country_name" */
    String strCountryName = c.getString(cursor.getColumnIndex("country_name"));
    

    See this snippet Genscripts in case you want a more complete one. Note that this is a parameterized SQL query, so in essence, it's a prepared statement.

提交回复
热议问题