SQLite与Android的数据交互

时间:2021-04-01 23:20:33

首先把db放在res的下方创一个raw文件夹,里面用来放db

创一个DbHelper类,实际代码如下:

 package com.laci.db;  

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
* Created by Laci on 2017/6/25.
*/

public class DbHelper extends SQLiteOpenHelper{
/**
*
* @param context 上下文
* @param name 数据库的名字
* @param factory 数据库工厂,null
* @param version 数据库的版本
*/
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}

@Override
public void onCreate(SQLiteDatabase db) {
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

然后再相同的目录下创一个DbManager类

package com.laci.db;  

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.zking.laci.android_project.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
* Created by Laci on 2017/6/27.
*/

public class DbManager {
public static final String DB_NAME = "wenwen.db"; //数据库名字
public static final String PACKAGE_NAME ="com.zking.laci.android_project";//包名
public static final String DB_PATH = "/data" + Environment.getDataDirectory().getAbsolutePath() + "/" + PACKAGE_NAME; //数据库的绝对路径( /data/data/com.*.*(package name))
private SQLiteDatabase db;
private Context context;

public DbManager(Context context) {
this.context = context;
}

//对外提供的打开数据库接口
public void openDataBase() {
this.db = this.openDataBase(DB_PATH + "/databases");
}

//获取打开后的数据库
public SQLiteDatabase getDb() {
return this.db;
}

// 本地打开数据方法
private SQLiteDatabase openDataBase(String filePath) {
try {
File file = new File(filePath);
if (!file.exists()) { //判断文件是否存在
//通过输入流和输出流,把数据库拷贝到"filePath"下
file.mkdir();
File file2=new File(filePath+"/"+DB_NAME);
if (!file2.exists()) {
InputStream is = context.getResources().openRawResource(R.raw.wenwen);//获取输入流,使用R.raw.test资源
FileOutputStream fos = new FileOutputStream(file2);
byte[] buffer = new byte[1024];
int readCount;
while ((readCount = is.read(buffer)) > 0) {
fos.write(buffer, 0, readCount);
}
fos.close();
is.close();
}
}
//打开数据库
SQLiteDatabase db =new DbHelper(context,"wenwen.db",null,2).getWritableDatabase();
return db;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

//关闭数据库
public void closeDataBase()
{
if(this.db!=null)
db.close();
}
}

最后在你第一个开始运行的activity中,写下以下代码

DbManager dbManager=new DbManager(getApplicationContext());  
dbManager.openDataBase();