下面是一个示例代码:
public class MyDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "my_database";
private static final int DATABASE_VERSION = 1;
private static MyDatabaseHelper instance;
public MyDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public static synchronized MyDatabaseHelper getInstance(Context context) {
if (instance == null) {
instance = new MyDatabaseHelper(context);
}
return instance;
}
@Override
public void onCreate(SQLiteDatabase db) {
// create tables, triggers, indexes etc
db.execSQL("CREATE TABLE my_table (id INTEGER PRIMARY KEY, name TEXT)");
db.execSQL("CREATE TRIGGER my_trigger AFTER INSERT ON my_table BEGIN INSERT INTO my_other_table (name) VALUES (new.name); END");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// upgrade database schema (e.g. alter table, add new table etc)
}
}
// 使用单一连接
public void doSomeDatabaseOperation() {
SQLiteDatabase db = MyDatabaseHelper.getInstance(context).getWritableDatabase();
// execute queries, insert, update or delete operations here
db.execSQL("INSERT INTO my_table (name) VALUES ('John Doe')");
// close the connection
db.close();
}