我有一个现有的数据库,我在sqlite数据库浏览器中创建了包含四个表并将其放在assets文件夹中。现在我想通过代码动态地将更多表添加到此数据库中。如何实现这一目标。
答案 0 :(得分:0)
首先,您需要通过创建以下内容来创建数据库:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydatabase.db";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE = "create table mutable (_id integer primary key autoincrement, field1 text not null, field2 text not null);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Method that creates database
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE);
}
}
感谢您需要创建一个DBAdabter类来操作该数据库中的数据:
public class DbAdapter {
private Context context;
private SQLiteDatabase database;
private DatabaseHelper dbHelper;
// Database fields
private static final String DATABASE_TABLE = "mutable";
public static final String KEY_ID = "_id";
public static final String KEY_FIELD1 = "field1";
public static final String KEY_FIELD2 = "field2";
public DbAdapter(Context context) {
this.context = context;
}
public DbAdapter open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
//Create data to be inserted in db
private ContentValues createContentValues(String field1, String field2) {
ContentValues values = new ContentValues();
values.put( KEY_FIELD1, field1 );
values.put( KEY_FIELD2, field2 );
return values;
}
//Insert in DB
public long Insert(String field1, String field2) {
ContentValues values = createContentValues(field1, field2);
return database.insertOrThrow(DATABASE_TABLE, null, values);
}
//OTHER METHODS FOR RETRIEVING DATA ETC
}