分享

Android程序中读取使用已有的SQLite数据库

 wwwijhyt图书馆 2020-07-25

方法一:

先在 Manifest 里添加权限

  1. <span style="font-size:12px;"><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  2. <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" /></span>
第一步先判断在指定的路劲是否存在,不存在就创建。第二步将android的资源下的数据库复制到指定路径下面。第三步就是根据指定路径打开或者创建数据库,然后得到操作数据库的对象,得到操作数据库的对象了,自然就可以对数据库中的表进行增删改查等操作了。
  1. <span style="font-size:12px;">SQLiteDatabase db;
  2. private final String DATABASE_PATH = android.os.Environment
  3. .getExternalStorageDirectory().getAbsolutePath() + "/vote";
  4. private String DATABASE_FILENAME = "db_vote.db";
  5. // 初始化数据库
  6. private SQLiteDatabase openDatabase() {
  7. try {
  8. String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
  9. File dir = new File(DATABASE_PATH);
  10. if (!dir.exists())
  11. dir.mkdir();
  12. if (!(new File(databaseFilename)).exists()) {
  13. InputStream is = getResources().openRawResource(R.raw.db_vote);
  14. FileOutputStream fos = new FileOutputStream(databaseFilename);
  15. byte[] buffer = new byte[8192];
  16. int count = 0;
  17. while ((count = is.read(buffer)) > 0) {
  18. fos.write(buffer, 0, count);
  19. }
  20. fos.close();
  21. is.close();
  22. }
  23. db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
  24. return db;
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. return null;
  29. }</span>
方法二:
1. 准备SQLite database文件

    假设你已经创建了一个sqlite数据库,我们需要对其进行一些修改。

   (译者注:这里原文是推荐了一个SQLite数据库管理软件,这个我觉得可以随自己的喜好,最Windows下面有多款可视化的SQlite数据库管理软件,可以方便的读取,编辑数据库,例如我用的是sqlitestudio

打开数据库,添加一个新的table “android_metadata",插入一行数据,具体的SQL如下:

  1. <span style="font-size:12px;"> CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US')
  2. INSERT INTO "android_metadata" VALUES ('en_US') </span>
(译者注:上面两行是表明需要进行的操作,具体可以直接在sqlitesstudio中完成)

    然后你需要对你数据表格的primary id 列重命名为 “_id”,这样Adroid会知道怎么对id列进行绑定,你可以很容易的在SQlite数据库管理软件中进行列编辑。

    这两步之后,你的sqlite数据库文件就准备好了。

  (这里我保留了id列,即没有对其进行重命名,测试证明也是没有问题的)

2. 在你的Android程序中复制,打开以及访问数据库

    现在把你上一步准备好的数据库文件放在“assets”文件夹下面,然后通过继承 SQLiteOpenHelper类来创建一个Database Helper类,

你的DataBaseHelper类大致可以如下:

  1. <span style="font-size:12px;">public class DataBaseHelper extends SQLiteOpenHelper{
  2. //The Android's default system path of your application database.
  3. private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
  4. private static String DB_NAME = "myDBName";
  5. private SQLiteDatabase myDataBase;
  6. private final Context myContext;
  7. /**
  8. * Constructor
  9. * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
  10. * @param context
  11. */
  12. public DataBaseHelper(Context context) {
  13. super(context, DB_NAME, null, 1);
  14. this.myContext = context;
  15. }
  16. /**
  17. * Creates a empty database on the system and rewrites it with your own database.
  18. * */
  19. public void createDataBase() throws IOException{
  20. boolean dbExist = checkDataBase();
  21. if(dbExist){
  22. //do nothing - database already exist
  23. }else{
  24. //By calling this method and empty database will be created into the default system path
  25. //of your application so we are gonna be able to overwrite that database with our database.
  26. this.getReadableDatabase();
  27. try {
  28. copyDataBase();
  29. } catch (IOException e) {
  30. throw new Error("Error copying database");
  31. }
  32. }
  33. }
  34. /**
  35. * Check if the database already exist to avoid re-copying the file each time you open the application.
  36. * @return true if it exists, false if it doesn't
  37. */
  38. private boolean checkDataBase(){
  39. SQLiteDatabase checkDB = null;
  40. try{
  41. String myPath = DB_PATH + DB_NAME;
  42. checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  43. }catch(SQLiteException e){
  44. //database does't exist yet.
  45. }
  46. if(checkDB != null){
  47. checkDB.close();
  48. }
  49. return checkDB != null ? true : false;
  50. }
  51. /**
  52. * Copies your database from your local assets-folder to the just created empty database in the
  53. * system folder, from where it can be accessed and handled.
  54. * This is done by transfering bytestream.
  55. * */
  56. private void copyDataBase() throws IOException{
  57. //Open your local db as the input stream
  58. InputStream myInput = myContext.getAssets().open(DB_NAME);
  59. // Path to the just created empty db
  60. String outFileName = DB_PATH + DB_NAME;
  61. //Open the empty db as the output stream
  62. OutputStream myOutput = new FileOutputStream(outFileName);
  63. //transfer bytes from the inputfile to the outputfile
  64. byte[] buffer = new byte[1024];
  65. int length;
  66. while ((length = myInput.read(buffer))>0){
  67. myOutput.write(buffer, 0, length);
  68. }
  69. //Close the streams
  70. myOutput.flush();
  71. myOutput.close();
  72. myInput.close();
  73. }
  74. public void openDataBase() throws SQLException{
  75. //Open the database
  76. String myPath = DB_PATH + DB_NAME;
  77. myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
  78. }
  79. @Override
  80. public synchronized void close() {
  81. if(myDataBase != null)
  82. myDataBase.close();
  83. super.close();
  84. }
  85. @Override
  86. public void onCreate(SQLiteDatabase db) {
  87. }
  88. @Override
  89. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
  90. }
  91. // Add your public helper methods to access and get content from the database.
  92. // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
  93. // to you to create adapters for your views.
  94. } </span>

就这样。

    现在你可以创建一个新的DataBaseHelper实例,然后调用createDataBase(),然后再调用openDataBase()方法,记住修改DB_PATH字符串中“YOUR_PACKAGE”为你真正的package名称(也就是说com.examplename.myapp)

以下是示范代码:

  1. <span style="font-size:12px;"> ...
  2. DataBaseHelper myDbHelper = new DataBaseHelper();
  3. myDbHelper = new DataBaseHelper(this);
  4. try {
  5. myDbHelper.createDataBase();
  6. } catch (IOException ioe) {
  7. throw new Error("Unable to create database");
  8. }
  9. try {
  10. myDbHelper.openDataBase();
  11. }catch(SQLException sqle){
  12. throw sqle;
  13. }
  14. ... </span>





    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多