Android Sqlite 使用封装
在Android中使用SQLite时,可以创建一个封装类来简化数据库的操作。以下是一个简单的封装类示例,它提供了基本的增删改查操作:
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "mytable";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ "ID INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "NAME TEXT,"
+ "AGE INTEGER" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
//插入数据
public boolean insertData(String name, int age) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", name);
contentValues.put("AGE", age);
long result = db.insert(TABLE_NAME, null, contentValues);
return result != -1;
}
//更新数据
public boolean updateData(String name, int age, int id) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", name);
contentValues.put("AGE", age);
int result = db.update(TABLE_NAME, contentValues, "ID = ?", new String[]{Integer.toString(id)});
return result > 0;
}
//删除数据
public boolean deleteData(int id) {
SQLiteDatabase db = this.getWritableDatabase();
int result = db.delete(TABLE_NAME, "ID = ?", new String[]{Integer.toString(id)});
return result > 0;
}
//查询数据
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
return db.query(TABLE_NAME, null, null, null, null, nul
评论已关闭