博
方法1已经讲述了一种初始化数据库的方法
它的数据库初始化不是用sql语句,而是用一个现成的sqlite的二进制文件进行直接copy到Android系统的数据库路径中。我一方面不太放心这种二进制文件的直接copy,另一方面,如果sqlite数据库的二进制结构有所升级或变动,我的程序就无法对所有sqlite版本兼容了。
方法2:在启动时,执行sql文件进行数据库初始化.
SQLiteOpenHelper的onCreate仅在程序第一次使用数据库时执行,然后执行onCreate;此后的执行就会跳过onCreate,直接执行onOpen。因此完全无需自己去检测数据库是否最在.
以下按照SQLiteOpenHelper的”正确“使用方法,本人写的SQLiteOpenHelper的子类,你可以用它初始你的Android数据库。数据库用sql语句形式,放在项目的res / raw目录底下,记住每行一条语句(因为我用readline()来读源文件),不能换行!你可以用本地数据库导出工具,此处省略数据导出。
代码如下:
Java代码
- /**
- *
- */
- package com.yourpackage;
- import java.io.BufferedReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.InputStreamReader;
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
- /**
- * @author fan.zhang
- *
- */
- public class DataBaseHelper extends SQLiteOpenHelper {
- private static String DB_PATH = "/data/data/your_package_name/databases/";
- private static final String DB_NAME = "your_db_name.db";
- private SQLiteDatabase myDataBase;
- private final Context myContext;
- public FileSQLiteHelp(Context context) {
- super(context, DB_NAME, null, 1);
- this.myContext = context;
- }
- /**
- * inital your database from your local res-raw-folder to the just created
- * empty database in the system folder, from where it can be accessed and
- * handled.
- * */
- private void initDataBase()throws IOException {
- // Open your local db as the input stream
- // InputStream myInput = myContext.getAssets().open(DB_NAME);
- InputStream myInput = myContext.getResources().openRawResource(
- R.raw.your_db_file_name);
- InputStreamReader reader = new InputStreamReader(myInput);
- BufferedReader breader = new BufferedReader(reader);
- // Path to the just created empty db
- String outFileName = DB_PATH + DB_NAME,
- str;
- // Open the empty db as the output stream
- FileWriter myOutput = new FileWriter(outFileName, true);
- while ((str = breader.readLine()) != null) {
- myDataBase.execSQL(str); //exec your SQL line by line.
- }
- // Close the streams
- myOutput.flush();
- myOutput.close();
- myInput.close();
- }
- /*
- * (non-Javadoc)
- *
- * @see
- * android.database.sqlite.SQLiteOpenHelper#onCreate(android.database.sqlite
- * .SQLiteDatabase)
- */
- @Override
- public void onCreate(SQLiteDatabase db) {
- // TODO Auto-generated method stub
- myDataBase = db;
- try {
- this.initDataBase();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- @Override
- public void onOpen(SQLiteDatabase db) {
- boolean readOnly = db.isReadOnly();
- }
- /*
- * (non-Javadoc)
- *
- * @see
- * android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
- * .SQLiteDatabase, int, int)
- */
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // TODO Auto-generated method stub
- }
- }
可以按正常逻辑用DataBaseHelper.getReadableDatabase()来使用你的数据库了。
时间: 2024-10-04 07:46:26