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

这里有2个思路

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

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

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

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

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

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

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

2.复制文件到应用中.

把第一步创建的数据库文件复制到应用中的assets文件夹, asserts文件夹的路径如下:

 

然后创建DateBaseHelper extends SQLiteOpenHelper的类文件.

代码如下:

Java代码
  1. 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. @Override
  88. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
  89. // Add your public helper methods to access and get content from the database.
  90. // You could return cursors by doing "return myDataBase.query(....)" so it'd be easy
  91. // to you to create adapters for your views.
  92. }

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

createDataBase() //创建

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

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

如:com.examplename.myapp

大概代码如下:

Java代码
  1. ...
  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. ...

android:Android中用文件初始化sqlite数据库的更多相关文章

  1. android:Android中用文件初始化sqlite数据库(zz)

        很多时候在应用安装初始化时,需要创建本地数据库,同时为数据库添加数据,之后再从数据库中读取数据. 这里有2个思路 1.先在本地创建一个能支持android使用的sqlite数据库文件,启动时, ...

  2. Android中用文件初始化sqlite 数据库(二)

    博 androidsqlite启动时数据库初始化  方法1已经讲述了一种初始化数据库的方法 它的数据库初始化不是用sql语句,而是用一个现成的sqlite的二进制文件进行直接copy到Android系 ...

  3. 在 Android 应用程序中使用 SQLite 数据库以及怎么用

    part one : android SQLite 简单介绍 SQLite 介绍 SQLite 一个非常流行的嵌入式数据库.它支持 SQL 语言,而且仅仅利用非常少的内存就有非常好的性能.此外它还是开 ...

  4. Android菜鸟成长记11 -- sqlite数据库的设计和升降级

    Google为Andriod的较大的数据处理提供了SQLite,他在数据存储.管理.维护等各方面都相当出色,功能也非常的强大.SQLite具备下列特点: 1.轻量级 使用 SQLite 只需要带一个动 ...

  5. Android内部自带的SQLite数据库操作dos命令

    1:什么叫做SQLite数据库 Android系统内核是Linux系统,Android系统很特殊,他自带了一个SQLite数据库,轻量型的一款嵌入式的数据库 它占用资源非常的低,在嵌入式设备中,可能只 ...

  6. 在Android中查看和管理sqlite数据库

    在Android中可以使用Eclipse插件DDMS来查看,也可以使用Android工具包中的adb工具来查看.android项目中的sqlite数据库位于/data/data/项目包/databas ...

  7. Android 批量插入数据到SQLite数据库

    Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式 ...

  8. Android批量插入数据到SQLite数据库

    Android中在sqlite插入数据的时候默认一条语句就是一个事务,因此如果存在上万条数据插入的话,那就需要执行上万次插入操作,操作速度可想而知.因此在Android中插入数据时,使用批量插入的方式 ...

  9. Android中多表的SQLite数据库(译)

    原文: Android SQLite Database with Multiple Tables 在上一篇教程Android SQLite Database Tutorial中,解释了如何在你的And ...

随机推荐

  1. ARC下循环引用的问题

    最初 最近在开发应用时碰到使用ASIHttpRequest后在某些机器上发不出请求的问题,项目开启了ARC,代码是这样写的: @implement MainController - (void) fe ...

  2. java高级编程-使用反射强制给private字段赋值

    转自:http://blog.csdn.net/yaerfeng/article/details/7103397 今天项目中遇到了一个问题,要调用一个类,并获取这个类的属性进行赋值然后将这个类传递到方 ...

  3. SilverLight:布局(2)GridSplitter(网格分割)垂直分割、水平分割

    ylbtech-SilverLight-Layout: 布局(2)GridSplitter(网格分割)垂直分割.水平分割 A, Splitter(分割)对象之 GridSplitter(网格分割)1: ...

  4. 数组全排列 knuth 分解质因数

    template<typename T> void swap(T* a, T* b) { T temp = *a; *a = *b; *b = temp; } //数组的全排列 void ...

  5. karaf中利用Bundle引入外部log4j配置文件

    环境准备: 1.在karaf_home下新建 config及logs目录 2.将mylog4j.properties拷贝到config文件夹下 查看log4j-1.2.17.jar/MANIFEST. ...

  6. 小白学phoneGap《构建跨平台APP:phoneGap移动应用实战》连载一(PhoneGap中的API)

    之前本博连载过<构建跨平台APP:jQuery Mobile移动应用实战>一书.深受移动开发入门人员的喜爱. 从如今開始,连载它的孪生姐妹书phoneGap移动应用实战一书,希望以前是小白 ...

  7. jquery中text(),html(),val()在取值上的区别

    1.html():读取和修改一个元素的HTML内容: 2.text():读取和修改一个元素的文本内容: 3.val():读取和修改一个表单元素的value字段值.

  8. 代码运行时间 检测锁及死锁详细信息,及sql语句 平台转化

    代码运行时间   System.Diagnostics.Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // 开始监视代码运行时间 ...

  9. angular input file 上传文件

    <body > <div ng-controller="fileCtrl"> <form ng-submit="submit(obj)&qu ...

  10. 各浏览器对常用或者错误的 Content-Type 类型处理方式不一致

    标准参考 content-type 用于定义用户的浏览器或相关设备如何显示将要加载的数据,或者如何处理将要加载的数据,此属性的值可以查看 MIME 类型. MIME (Multipurpose Int ...