对数据库表进行操作
接下来讨论具体如何插入数据、查询数据、删除数据等等。调用 getReadableDatabase() 或 getWriteableDatabase() 方法,你可以得到 SQLiteDatabase 实例,具体调用那个方法,取决于你是否需要改变数据库的内容。有两种方法可以对数据库表进行操作:使用execSQL方法执行SQL语句;使用insert、delete、update和query方法,把SQL语句的一部分作为参数。
插入数据:
使用SQLiteDatabase.insert()方法来插入数据:
public voidinsert(int formCode, String summary, String context, String folder) { Log.i("SQLite", "----insert----"); ContentValues values = new ContentValues(); values.put("formcode", formCode); values.put("date", (new TaskDate()).toString()); values.put("summary", summary); values.put("context", context); values.put("imagefolder", folder); SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { db.insert("draftbox",null, values);db.setTransactionSuccessful(); } catch (Exception e) { return ; } finally { db.endTransaction(); } db.close();} |
使用SQLiteDatabase.execSQL()方法来插入数据:
public int insert(Person person) { Log.i("SQLite", "----insert----"); SQLiteDatabase db = getWritableDatabase(); db.beginTransaction(); try { db.execSQL("insert into " + "draftbox" + " values(?, ?, ?, ?)", new Object[] { person.formCode, person.summary, person.context, person.folder}); db.setTransactionSuccessful(); } catch (Exception e) { return 0; } finally { db.endTransaction(); } db.close(); return 1; } |
删除数据:
使用SQLiteDatabase.delete()方法来删除数据(删除所有数据db.delete(<表名>, null, null)):
public int delete(Person person) { |
使用SQLiteDatabase.execSQL()方法来删除数据:
public int delete(Person person) { |