Android中用文件初始化sqlite 数据库的文(一) (转)

摘要:
很多时候,在安装和初始化应用程序时,需要创建本地数据库,向数据库中添加数据,然后从数据库中读取数据。

很多时候在应用安装初始化时,需要创建本地数据库,同时为数据库添加数据,之后再从数据库中读取数据。

这里有2个思路

1.先在本地创建一个能支持android使用的sqlite数据库文件,启动时,用现成的sqlite的二进制文件进行直接copy到Android系统的数据库路径

2.可以考虑在第一次启动时,执行数据库初始化的sql文件.

方法1:

1.在本地准备android能使用的sqlite数据库文件

使用sqlite数据库管理工具,看个人爱好(SQLite Database Browser ,Navicat Premium,)

打开数据库,创建"android_metadata"数据表

Sql代码 
CREATE TABLE "android_metadata" ("_id"  INTEGER PRIMARY KEY AUTOINCREMENT,"locale" TEXT DEFAULT 'en_US');//创建表
INSERT INTO "android_metadata" VALUES (1,'en_US');//插入值

 创建其他应用需要的表..此处省略.

2.复制文件到应用中.

把第一步创建的数据库文件复制到应用中的assets文件夹,然后创建DateBaseHelper extends SQLiteOpenHelper的类文件.

代码如下:

public class DataBaseHelper extends SQLiteOpenHelper {
    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/YOUR_PACKAGE/databases/";
    private static String DB_NAME = "myDBName";
    private SQLiteDatabase myDataBase;
    private final Context myContext;
    /**
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     */
    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own database.
     * */
    public void createDataBase()throws IOException {
        boolean dbExist = checkDataBase();
        if (dbExist) {
            //do nothing - database already exist
        } else {
            //By calling this method and empty database will be created into the default system path
            //of your application so we are gonna be able to overwrite that database with our database.
            this.getReadableDatabase();
            try {
                copyDataBase();
            } catch (IOException e) {
                throw new Error("Error copying database");
            }
        }
    }

    /**
     * Check if the database already exist to avoid re-copying the file each time you open the application.
     * @return true if it exists, false if it doesn't
     */
    private boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            //database does't exist yet.
        }

        if (checkDB != null) {
            checkDB.close();
        }
        return checkDB != null ? true : false;
    }

    /**
     * Copies your database from your local assets-folder to the just created empty database in the
     * system folder, from where it can be accessed and handled.
     * This is done by transfering bytestream.
     * */
    private void copyDataBase()throws IOException {
        //Open your local db as the input stream
        InputStream myInput = myContext.getAssets().open(DB_NAME);
        // Path to the just created empty db
        String outFileName = DB_PATH + DB_NAME;
        //Open the empty db as the output stream
        OutputStream myOutput = new FileOutputStream(outFileName);
        //transfer bytes from the inputfile to the outputfile
        byte[]buffer = new byte[1024];
        int length;
        while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
        }

        //Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();
    }

    public void openDataBase()throws SQLException {
        //Open the database
        String myPath = DB_PATH + DB_NAME;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
    }

    @Override
    public synchronized void close() {
        if (myDataBase != null)
            myDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {}

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
    // Add your public helper methods to access and get content from the database.
    // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
    // to you to create adapters for your views.
}

3.现在我们可以创建DateBaseHelper的实现操作了.

createDataBase() //创建

openDataBase()//打开只读数据库

记得要更改"YOUR_PACKAGE"为你的应用的包名

如:com.examplename.myapp

大概代码如下:

...
DataBaseHelper myDbHelper = new DataBaseHelper();
myDbHelper = new DataBaseHelper(this);
try {
    myDbHelper.createDataBase();
} catch (IOException ioe) {
    throw new Error("Unable to create database");
}
try {
    myDbHelper.openDataBase();
} catch (SQLException sqle) {
    throw sqle;
}
...

 转自:http://zhangfan822.iteye.com/blog/1883829

免责声明:文章转载自《Android中用文件初始化sqlite 数据库的文(一) (转)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Android学习之五:android一些基本控件Spring配置文件中<bean>标签的scope属性下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

srand函数

srand函数是随机数发生器的初始化函数。  原型:void srand(unsigned seed);  用法:它需要提供一个种子,这个种子会对应一个随机数,如果使用相同的种子后面的rand()函数会出现一样的随机数。如: srand(1); 直接使用1来初始化种子。不过为了防止随机数每次重复常常使用系统时间来初始化,即使用 time函数来获得系统时间,...

cad.net 文字偏移及符号表

bug:字体偏移 动图演示:绑定参照后出现 动图演示:代码克隆后出现 有问题的代码 using Autodesk.AutoCAD.ApplicationServices; using Autodesk.AutoCAD.DatabaseServices; using Autodesk.AutoCAD.EditorInput; using Autodes...

记一次MySQL数据库拒绝访问的解决过程

问题背景 用wordpress搭博客,数据库采用MySQL。为了调试方便,创建账户my_account ,允许它从任意主机访问数据库。 CREATE USER `my_account`@'%' IDENTIFIED BY 'my_password'; 修改 wp-config.php 相应配置,注意 DB_HOST 设置为 127.0.0.1。 defi...

C#学习笔记(3)——操作sqlserver数据库增删改查

说明(2017-5-25 16:29:35): 1. VS2010,视图->服务器资源管理器->数据连接->右键添加连接->服务器名(本机可以用点)->选择数据库->高级里面可以看其他选项,及连接字符串 2. 连接字符串 (1)string str = "Data Source=.; Initial Catalog=j...

ORB-SLAM3 单目地图初始化(终结篇)

作者: 乔不思 来源:微信公众号|3D视觉工坊(系投稿) 3D视觉精品文章汇总:https://github.com/qxiaofan/awesome-3D-Vision-Papers/ 一、前言 请阅读本文之前最好把ORB-SLAM3的单目初始化过程再过一遍(ORB-SLAM3 细读单目初始化过程(上)、超详细解读ORB-SLAM3单目初始化(下篇)),...

把sql server 数据库中数据导出至excel表

https://blog.csdn.net/weixin_42596182/article/details/90750187 打开数据库后选择需要导出数据的数据库,比如本次为db_PMMS,右键选择“任务”–“导出数据”,点击下一步。 进入“选择数据源”窗口。“数据源”选择sql server native client 10.0,然后选择服务器和数据...