如何导入已有数据库

来源:2-1 sqlite数据表查询(上)

滄梧

2020-01-18 23:40

//我已经有数据库了,如何导入并查询呢

写回答 关注

1回答

  • 慕梦前来
    2020-06-08 21:21:48

    操作方法:1. 把原数据库包括在项目源码的 res/raw 目录下,然后建立一个DBManager类,代码如下:

    12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758package com.android.ImportDatabase; import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream; import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.os.Environment;import android.util.Log; public class DBManager {    private final int BUFFER_SIZE = 400000;    public static final String DB_NAME = "countries.db"; //保存的数据库文件名    public static final String PACKAGE_NAME = "com.android.ImportDatabase";    public static final String DB_PATH = "/data"            + Environment.getDataDirectory().getAbsolutePath() + "/"            + PACKAGE_NAME;  //在手机里存放数据库的位置     private SQLiteDatabase database;    private Context context;     DBManager(Context context) {        this.context = context;    }     public void openDatabase() {        this.database = this.openDatabase(DB_PATH + "/" + DB_NAME);    }     private SQLiteDatabase openDatabase(String dbfile) {        try {            if (!(new File(dbfile).exists())) {  //判断数据库文件是否存在,若不存在则执行导入,否则直接打开数据库                InputStream is = this.context.getResources().openRawResource(                        R.raw.countries); //欲导入的数据库                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();            }            SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile,                    null);            return db;        } catch (FileNotFoundException e) {            Log.e("Database", "File not found");            e.printStackTrace();        } catch (IOException e) {            Log.e("Database", "IO exception");            e.printStackTrace();        }        return null;    }


Android基础教程-SQLite高级操作

本视频教程讲解Sqlite数据库查询和事务操作以及将数据分页加载

13982 学习 · 18 问题

查看课程

相似问题