1.创建SQLiteOpenHelper对象;
参考代码如下:
public class DBHelper extends SQLiteOpenHelper{
2.使用SQLiteOpenHelper的getReadableDatebase()或者getWritableDatabase()获取SQLiteDataBase对象:
参考代码如下:
//创建时会自动调用onCreate()方法;
DBHelper dbHelper = new DBHelper(SQliteActivity.this, "test_qq_db");
SQLiteDatabase db = dbHelper.getWritableDatabase();
//更新数据库版本时会自动调用onUpgrade()方法:
DBHelper dbHelper = new DBHelper(SQliteActivity.this, "test_qq_db", 2);
SQLiteDatabase db = dbHelper.getReadableDatabase();
3.增删改查操作代码如下:
//增加数据
ContentValues values = new ContentValues();
values.put("id", 1);//id 是列名,1是该列的值
values.put("user_name", "qinqin");
SQLiteDatabase db = getObjectDb();
db.insert("user", null, values);
//更新数据
ContentValues values = new ContentValues();
values.put("user_name", "huangqin");
// 表名 ContentValues对象 where条件 参数
db.update("user", values, "id = ?", new String[]{"1"});
//查询数据
Cursor cursor = db.query("user", new String[]{"id","user_name"}, "id=?", new String[]{"1"}, "", "", "");
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("user_name"));
System.out.println(name);
}