須要更改代碼中的數據庫文件名和工程包名java
外部數據庫放置在assets目錄中android
package utils; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import android.content.Context; import android.os.Environment; public class ImportDB{ private final int BUFFER_SIZE = 10000; public static final String DB_NAME = "sqlserver"; //被保存讀取的數據庫文件名 public static final String PACKAGE_NAME = "com.example.imagetostring";//工程包名 public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME+"/databases"; //在手機裏存放數據庫的位置 private Context context; public ImportDB(Context context) { this.context = context; } public void copyDatabase() { String dbfile=DB_PATH + "/" + DB_NAME ; try { //執行數據庫導入 InputStream is = this.context.getResources().getAssets().open("sqlserver"); //欲導入的數據庫 FileOutputStream fos = new FileOutputStream(dbfile); byte[] buffer = new byte[BUFFER_SIZE]; int count = 0; while ((count = is.read(buffer)) > 0) { fos.write(buffer, 0, count); } fos.close();//關閉輸出流 is.close();//關閉輸入流 } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
主函數調用sql
// 導入外部數據庫 ImportDB db = new ImportDB(context); db.copyDatabase();
導入完成後效果圖數據庫
聲明數據庫ide
package db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; class sqlServer extends SQLiteOpenHelper { private final static String DB_NAME = "sqlserver";// 數據庫名稱 public final static int DataBase_Version = 1; public sqlServer(Context context) { super(context, DB_NAME, null, DataBase_Version); } @Override public void onCreate(SQLiteDatabase db) { // String createDB = "create table " + DB_NAME // + "(cityid varchar(14) primary key , cityname varchar(20),type // int)";// 數據庫中記錄的屬性名稱及屬性值類型 // db.execSQL(createDB);// 建立數據庫 } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // String dropTableSQL = "DROP TABLE IF EXISTS " + DB_NAME + " "; // db.execSQL(dropTableSQL); // dropTableSQL = "DROP TABLE IF EXISTS " + DB_NAME + " "; // db.execSQL(dropTableSQL); // onCreate(db); } }
調用數據庫函數
package db; import android.content.Context; import android.database.sqlite.SQLiteDatabase; public class sqlDao { public static SQLiteDatabase gRSqliteDB = null; public static SQLiteDatabase gWSqliteDB = null; // -----獲取可讀寫數據庫 public static boolean getDataBase(Context context) { try { sqlServer dbHelper = new sqlServer(context); if (gRSqliteDB == null) { gRSqliteDB = dbHelper.getReadableDatabase(); } if (gWSqliteDB == null) { gWSqliteDB = dbHelper.getWritableDatabase(); } } catch (Exception e) { return false; } return true; } // ----數據庫關閉 public static void CloseDataBase() { if (gWSqliteDB != null) { gWSqliteDB.close(); } if (gRSqliteDB != null) { gRSqliteDB.close(); } } }