gpt4 book ai didi

java - Android 如何追加 SQLite 数据库

转载 作者:行者123 更新时间:2023-12-01 15:40:05 24 4
gpt4 key购买 nike

我有一个从我的 Assets 文件夹中的文件创建的数据库。当应用程序升级时,我希望该文件夹中的新文件添加(追加)到当前数据库。我目前正在尝试使用下面的这个脚本,但它不起作用。我只是没有添加到数据库。

        //Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(STATIC_DB_NAME);

// Path to the just created empty db
String outFileName = STATIC_DB_PATH + STATIC_DB_NAME;

//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);

//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}

//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();

最佳答案

您应该考虑使用 SQLLiteOpenHelper并实现 onUpgrade 方法。在该方法中(仅当您的数据库版本号(您维护的东西)递增时调用),您可以打开 Assets 文件并使用它对 sqllite 数据库执行插入/更新。

因此,在这种情况下,将 SQL 命令存储在文件中,然后读取每一行并使用 db.execSQL 运行:

BufferedReader reader = new BufferedReader(new FileReader(STATIC_DB_NAME));
String line = reader.readLine();
while(line != null){
db.execSQL(line);
line = reader.readLine();
}
reader.close();

关于java - Android 如何追加 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8201456/

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