80,359
社区成员
发帖
与我相关
我的任务
分享
public class DbSetup {
public Context context;
public String dbName = "mbook.lit"; //数据库名称(也是文件名称)
public String displayDbName = "mbook"; //数据库显示名称,对应phoneGap的显示名称
public int dbSize = 4194304; //数据库文件最大容量
public String dbDirName = "file__0"; //数据库保存的目录,默认。
public int dbDirSize = 104857600; //数据库目录最多文件容量。
public String DBPath; //数据库最终路径
public String phoneGapDBPath; //phoneGap数据库目录路径
public String phoneGapDBName; //phoneGap数据库名称
public void SetDatabase(Context context){
this.context = context;
phoneGapDBPath =context.getDir("database", 0).getPath();
phoneGapDBName = phoneGapDBPath + File.separator + "Databases.db";
DBPath = phoneGapDBPath + File.separator + dbDirName;
if(!checkDataBaseFile()){
try {
copyDataBase();
} catch (IOException e) {
throw new Error("拷贝数据库发生错误");
}
}
updateDBInfo();
}
private void updateDBInfo() {
// TODO 自动生成的方法存根
String ctorigins = "CREATE TABLE IF NOT EXISTS Origins ( origin TEXT , quota integer ) ";
String ctdatabases = "CREATE TABLE IF NOT EXISTS Databases ( guid integer primary key autoincrement , origin TEXT , name TEXT ,displayName Text ,estimatedSize interger ,path TEXT)";
SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(phoneGapDBName,null);
db.execSQL(ctorigins);
db.execSQL(ctdatabases);
Cursor cur1 = db.rawQuery("select * from Origins where origin = \"" + dbDirName + "\"",null);
if(cur1.getCount() == 0){
String sql1 = "insert into Origins values (\"" + dbDirName + "\" , " + dbDirSize + ")";
db.execSQL(sql1);
}
cur1.close();
cur1 = null;
Cursor cur2= db.rawQuery("select * from Databases where name = \"" + dbName +"\" and displayName=\"" + displayDbName + "\"" ,null);
if(cur2.getCount() == 0){
String sql2 = "insert into Databases values (null , \""+dbDirName+"\" , \"" + dbName + "\" , \"" + displayDbName + "\" , " + dbSize + " , \"" + dbName + "\")";
db.execSQL(sql2);
}
cur2.close();
cur2 = null;
db.close();
db = null;
}
public void copyDataBase() throws IOException {
String databaseFilenames = DBPath + File.separator + dbName;
File dir = new File(DBPath);
if (!dir.exists())// 判断文件夹是否存在,不存在就新建一个
dir.mkdir();
FileOutputStream os = new FileOutputStream(databaseFilenames);// 得到数据库文件的写入流
InputStream is = context.getResources().openRawResource(R.raw.mbook);// 得到数据库文件的数据流
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
is.close();
os.close();
}
public boolean checkDataBaseFile() {
String databaseFilename = DBPath + File.separator + dbName;
File dbFile = new File(databaseFilename);
return dbFile.exists();
}
}