在 PhoneGap 应用程序中预填充 SQLite 数据库
1) 您可以借助 SQLite Manager 等工具为应用创建基本数据库,或者如果您的应用中已有数据库,则可以直接获取数据库文件。
2) 然后你需要通过 CLI 安装 Cordova/PhoneGap SQLitePlugin。 (Cordova/PhoneGap SQLitePlugin)
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
3) 在您的 html 中添加以下脚本文件。
<script src="plugins/com.brodysoft.sqlitePlugin/www/SQLitePlugin.js"></script>
4) 如果您正在使用模拟器,请使用命令提示符复制您的数据库,我已在资产文件夹中添加 myDB.sqlite 然后运行。
adb push myDB.sqlite /data/data/com.my_app.my_app/databases/myDB.sqlite
5) 对于设备,只需将它们放入应用程序包中,即 Android 的资产文件夹。你需要 myDB.sqlite 和 file__0/0000000000000001.sqlite 文件。
6) 现在您必须在应用程序首次启动时将文件复制到应用程序的本地位置,并确保在您第一次 SQLite 查询之前复制文件。要复制这些文件,您可以根据您的环境使用以下代码 sn-p。 JAVA(安卓)。 More...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.init();
try {
String pName = this.getClass().getPackage().getName();
this.copy("myDB.sqlite", "/data/data/" + pName + "/databases/");
this.copy("0000000000000001.sqlite", "/data/data/" + pName + "/app_database/file__0/");
} catch (IOException e) {
e.printStackTrace();
}
super.loadUrl(Config.getStartUrl());
}
void copy(String file, String folder) throws IOException {
File CheckDirectory;
CheckDirectory = new File(folder);
if (!CheckDirectory.exists()) {
CheckDirectory.mkdir();
}
InputStream in = getApplicationContext().getAssets().open(file);
OutputStream out = new FileOutputStream(folder + file);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in .close();
out.close();
}
7) 然后在你的js文件中添加sn-p。
$(document).ready(function(e){
document.addEventListener("deviceready", dbConnection, false);
})
function dbConnection(){
db = window.sqlitePlugin.openDatabase("myDB.sqlite", "1.0", "DB", 2000000);
db.transaction(function(tx) {
tx.executeSql("SELECT * from table", [], function(tx, res) {
for(var i=0; i<res.rows.length; i++){ ;
console.log("RESULT:" + res.rows.item(i)['field_name']);
}
});
});
}
More Detail...