how to represtnt sqlite query in android?
I want to represnet this sql query in Sqlite in android ?
select id,name,t开发者_如何学Pythonopic from books where id=1 and topic ="art"
run a query on your SQLiteDatabase
object and save it in a Cursor
:
Cursor c = myDatabase.rawQuery("select id,name,topic from books where id = ? and topic = ?", new String[] {"1", "art"});
You have to use cursor as you can see in my example:
protected SQLiteDatabase dataDB;
//Get DB
Context context = getBaseContext();
LocationBookSQLite dbHelper = new LocationBookSQLite(context);
dataDB = dbHelper.getReadableDatabase();
//use a cursor to get db elements
Cursor cur = dataDB.query(books,
null, null, null, null, null, null);
cur.moveToFirst();
while (cur.isAfterLast() == false) {
if ( cur.getString(1).equals(1) && cur.getString(3).equals("art")) {
//here 1 mean the index of id
System.out.println(cur.getString(1));
//here 2 mean the index of name
System.out.println(cur.getString(2));
//here 3 mean the index of topic
System.out.println(cur.getString(3));
}
cur.moveToNext();
}
cur.close();
Create Class which handle all query execution like this
public Cursor getData(Context context, DBHelper dbHelper, String columnName,
String tableName, String where) {
query = "SELECT " + columnName + " FROM " + tableName + " " + where;
cursor = dmsUtility.rawQueryDataAttach(context, dbHelper, query);
return cursor;
}
public boolean insertData(Context context, DBHelper dbHelper, String
columnName,String valueData, String tableName, String where) {
query = "INSERT INTO " + tableName + " " + columnName + " VALUES ("
+ valueData + " )" + where;
dmsUtility.execSQLAttach(context, dbHelper, query);
return true;
}
public boolean updateData(Context context, DBHelper dbHelper, String
columnName, String tableName, String where) {
query = "UPDATE " + tableName + " SET " + columnName + " " + where;
dmsUtility.execSQLAttach(context, dbHelper, query);
return true;
}
And call function
DMSConstant.COLUMNNAME = "select id,name,topic";
DMSConstant.TABLENAME = "from books";
DMSConstant.WHERE = "where id=1 and topic ="art" ";
Cursor cursorBody = dbHelper.getData(getContext(), dbHelper,
DMSConstant.COLUMNNAME, DMSConstant.TABLENAME, DMSConstant.WHERE);
精彩评论