时间:2021-07-01 10:21:17 帮助过:15人阅读
具体使用方式:
public class DbTest { private static MyDBHelper dbHelper = null; private static void createTable(Context context){ if(dbHelper == null){ dbHelper = new MyDBHelper(context); } } private static void insertTest(){ SQLiteDatabase db = dbHelper.getWritableDatabase(); db.beginTransaction(); db.execSQL("insert into " + MyDBHelper.TABLE_NAME + " (id, name, age, address) values(1, ‘Jack‘, 25, ‘beijing‘ )"); db.execSQL("insert into " + MyDBHelper.TABLE_NAME + " (id, name, age, address) values(2, ‘Green‘, 26, ‘shanghai‘ )"); db.execSQL("insert into " + MyDBHelper.TABLE_NAME + " (id, name, age, address) values(3, ‘Herry‘, 27, ‘nanjing‘ )"); // db.setTransactionSuccessful(); // db.beginTransaction(); ContentValues values = new ContentValues(); values.put("id", 4); values.put("name", "Mary"); values.put("age", 28); values.put("address", "shenzhen"); db.insertOrThrow(MyDBHelper.TABLE_NAME, null, values); db.setTransactionSuccessful(); db.endTransaction(); } private static void queryTest(){ SQLiteDatabase db = dbHelper.getWritableDatabase(); String[] colums = new String[]{"id", "name", "age", "address"}; Cursor cursor = db.query(MyDBHelper.TABLE_NAME, colums, null, null, null, null, null); if(cursor!=null && cursor.getCount()>0){ while(cursor.moveToNext()){ int id = cursor.getInt(cursor.getColumnIndex("id")); String name = cursor.getString(cursor.getColumnIndex("name")); int age = cursor.getInt(cursor.getColumnIndex("age")); String address = cursor.getString(cursor.getColumnIndex("address")); Log.i(MainActivity.TAG, "(" + id + ", " + name + ", " + age + ", " + address + ")"); } } cursor.close(); } private static void deleteTest(){ SQLiteDatabase db = dbHelper.getWritableDatabase(); // String sql = "delete from " + MyDBHelper.TABLE_NAME + " where name = ‘Green‘"; // db.execSQL(sql); db.beginTransaction(); db.delete(MyDBHelper.TABLE_NAME, "name=?", new String[]{"Green"}); db.setTransactionSuccessful(); // db.endTransaction(); } private static void updateTest(){ SQLiteDatabase db = dbHelper.getWritableDatabase(); // String sql = "update " + MyDBHelper.TABLE_NAME + " set name=‘change‘ where age=27"; // db.execSQL(sql); db.beginTransaction(); ContentValues values = new ContentValues(); values.put("name", "change1"); db.update(MyDBHelper.TABLE_NAME, values, "age=?", new String[]{"27"}); db.setTransactionSuccessful(); db.endTransaction(); } public static void dbTest(Context context){ createTable(context); insertTest(); queryTest(); // deleteTest(); // queryTest(); updateTest(); queryTest(); } }
SQlite使用
标签:ack where new exec ade beijing put res main