在这里,使用扩展 SQLiteOpenHelper 的这个例子
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class YourSQLAdapter {
public static final String DBNAME = "filename.db";
public static final String TABLE = "tablename";
public static final int VERSION = 1;
public static final String KEY_ID = "_id";
// Add other fields here
private SQLiteDatabase sqLiteDatabase;
private SQLiteHelper sqLiteHelper;
private Context mContext;
//this is how I write the create db script, you may do it you own way;)
public static String a = "TEXT";
public static String b = "INTEGER";
public static String c = "PRIMARY KEY";
public static String d = "AUTOINCREMENT";
public static String e = " ";
public static String f = ",";
private static final String SCRIPT_CREATE_DATABASE =
"CREATE TABLE IF NOT EXISTS " + TABLE + e + "(" +
KEY_ID + e + b + e + c + e + d + f + e + ");";
public YourSQLAdapter(Context context){
mContext = context;
}
public void close() {
sqLiteHelper.close();
}
public int deleteAll() {
return sqLiteDatabase.delete(TABLE, null, null);
}
public long insert(String value) {
ContentValues cv = new ContentValues();
rooster.put("fieldname(or use its key value)", value);
return sqLiteDatabase.insert(TABLE, null, cv);
}
public YourSQLAdapter openToRead() throws SQLException {
try {
sqLiteHelper = new SQLiteHelper(mContext, DBNAME, null, 1);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
} catch (Exception e){}
return this;
}
public YourSQLAdapter openToWrite() throws SQLException {
try {
sqLiteHelper = new SQLiteHelper(mContext, DBNAME, null, 1);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
} catch (Exception e){}
return this;
}
public Cursor queueAll() {
String[] KEYS = { KEY_ID /* and all other KEYS*/ };
return sqLiteDatabase.query(TABLE, KEYS, null, null, null, null, null);
}
public Cursor queueDay(String query) {
String[] KEYS = { KEY_ID /* and all other KEYS*/ };
return sqLiteDatabase.query(TABLE, KEYS, query, null, null, null, null);
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
public void onCreate(SQLiteDatabase db) {
db.execSQL(SCRIPT_CREATE_DATABASE);
}
public void onUpgrade(SQLiteDatabase db, int oldversion, int newversion) {}
}
}
创建数据库时使用
YourSQLAdapter sql = new YourSQLAdapter(context);
sql.openToWrite();
如果您想从数据库中读取,请使用
YourSQLAdapter sql = new YourSQLAdapter(context);
sql.openToRead();
警告,如果尚未创建数据库,则会在 openToRead() 上出现异常,因为 SQLiteOpenHelper 认为它尚不存在并尝试创建它(因为它无法写入而无法创建)
希望这可以帮助;)