gpt4 book ai didi

android - 一次向sqlite数据库添加数据,多次读取

转载 作者:太空狗 更新时间:2023-10-29 16:38:10 25 4
gpt4 key购买 nike

我是 sqlite 的新手。在我的 android 项目中,我有一个数据库,我只需要将这些数据一次添加到应用程序中。(不要在应用程序运行时每次都插入数据)。我怎样才能完成这个任务?

我试着创造

public class DatabaseHandler extends SQLiteOpenHelper {

}

并在MainActivityonCreate方法中调用这个类

最佳答案

在 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
}

}

关于android - 一次向sqlite数据库添加数据,多次读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23085040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com