Android 数据库封装(SQLite)
以下是一个简单的Android SQLite数据库封装示例。这个例子展示了如何创建一个User
表,并包含了基本的增删查改操作。
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class UserDbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "user_database.db";
private static final int DB_VERSION = 1;
private static final String TABLE_NAME = "users";
public UserDbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "name TEXT,"
+ "email TEXT,"
+ "age INTEGER" + ")";
db.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
db.execSQL(DROP_TABLE);
onCreate(db);
}
public boolean insertUser(User user) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("INSERT INTO " + TABLE_NAME + " (name, email, age) VALUES (?, ?, ?)",
new Object[]{user.getName(), user.getEmail(), user.getAge()});
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
db.endTransaction();
db.close();
}
}
public boolean deleteUser(int id) {
SQLiteDatabase db = this.getWritableDatabase();
db.beginTransaction();
try {
db.execSQL("DELETE FROM " + TABLE_NAME + " WHERE id = ?", new Object[]{id});
db.setTransactionSuccessful();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
db.endTransaction();
db.close();
}
}
public User getUser(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE id = ?", new String[]{String.valueOf(id)});
if (cursor.moveToFirst()) {
return new User(cur
评论已关闭