注意:android
a, 將隨apk發佈的數據庫放在android工程下/res/raw路徑下。sql
b, 數據庫文件存到手機上時,路徑在/data/data/你的包名/databases下,其餘路徑則會出錯。數據庫
須要直接在工程裏新建數據庫時,會繼承SQLiteOpenHelper,但本文講的是隨apk一塊兒發佈數據庫的狀況,所以沒有必要繼承SQLiteOpenHelper,但也須要對test.db作一層包裝,在對test.db進行包裝的類對數據庫進行操做。ui
編寫程序的過程當中常常改變數據庫的結構,此時能夠經過數據庫版本號來判斷是否應該更新手機上的數據庫,sqlite中數據庫的user_version提供了這個幫助。下面的命令能夠更改數據庫的user_version,user_version必須是整數型的。this
PRAGMA [database.]user_version = 2 ;
下面是實現代碼,包括將數據庫寫到手機上以及對數據庫進行更新。spa
1 public class TestSqlDatabase{ 2 3 private static final String DATABASE_PATH = "/data/data/your.package.name/databases"; 4 5 private static final int DATABASE_VERSION = 0; 6 7 private static final String DATABASE_NAME = "test.db"; 8 9 private static String outFileName = DATABASE_PATH + "/" + DATABASE_NAME; 10 11 private Context context; 12 13 private SQLiteDatabase database; 14 15 public TestSqlDatabase(Context context) { 16 this.context = context; 17 18 File file = new File(outFileName); 19 if (file.exists()) { 20 database = SQLiteDatabase.openOrCreateDatabase(outFileName, null); 21 if (database.getVersion() != DATABASE_VERSION) { 22 database.close(); 23 file.delete(); 24 } 25 } 26 try { 27 buildDatabase(); 28 } catch (Exception e) { 29 e.printStackTrace(); 30 } 31 32 } 33 34 private void buildDatabase() throws Exception{ 35 InputStream myInput = context.getResources().openRawResource(R.raw.test); 36 File file = new File(outFileName); 37 38 File dir = new File(DATABASE_PATH); 39 if (!dir.exists()) { 40 if (!dir.mkdir()) { 41 throw new Exception("建立失敗"); 42 } 43 } 44 45 if (!file.exists()) { 46 try { 47 OutputStream myOutput = new FileOutputStream(outFileName); 48 49 byte[] buffer = new byte[1024]; 50 int length; 51 while ((length = myInput.read(buffer))>0){ 52 myOutput.write(buffer, 0, length); 53 } 54 myOutput.close(); 55 myInput.close(); 56 } catch (Exception e) { 57 e.printStackTrace(); 58 } 59 60 } 61 } 62 }