我是sqlite
的新手。在我的android项目中,我有一个数据库,我只需要将这些数据一次添加到应用程序。(不要在app运行时每次都插入数据)。我怎样才能完成这项任务?
我尝试创建
public class DatabaseHandler extends SQLiteOpenHelper {
}
并在onCreate
MainActivity
方法中调用此类
答案 0 :(得分:5)
在SQLiteOpenHelper中有一个方法只调用一次,它只是 onCreate 方法。因此,如果您只需要在数据库中添加数据一次,则必须在此方法中执行此操作。
但是如果由于某种原因你想要向数据库添加更多数据,你可以在 onUpgrade 方法中进行这次。
举个简单的例子:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "dbName";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "tableName";
public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
//this function called only once ever in the life of the app
@Override
public void onCreate(SQLiteDatabase database) {
//Create database query
database.execSQL("create table " + TABLE_NAME + " (column1 type, columun2 type...); ");
//Insert query
database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
database.execSQL("insert into " + TABLE_NAME + " values(value1,value2...);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//add more insert query if you need to add more datas after, but you have first to upgrade your DATABASE_VERSION to a higher number
}
}