要在Android系统中操作SQLite数据库,是通过Android的核心类SQLiteDatabase类来实现的,通常情况下为了数据库升级的需要以及使用方便,我们会选择继承SQLiteOpenHelper抽像类,但是SQLiteOpenHelper会将数据库文件创建在一个固定的目录(内存的/data/data/目录中),如果你想使用已经存在的数据库文件也就是说数据库会和程序一起发布,就得通过使用SQLiteDabase的静态方法OpenOrCreateDatabase()方法来得到SQLiteDabase对象,下面是一个具体操作类:
package net.my.dao;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import net.my.jokebook.R;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class DBHelper {
//得到SD卡路径
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/joke";
private final Activity activity;
//数据库名
private final String DATABASE_FILENAME;
public DBHelper(Context context) {
// TODO Auto-generated constructor stub
//这里直接给数据库名
DATABASE_FILENAME = "jokebook.db3";
activity = (Activity)context;
}
//得到操作数据库的对象
public SQLiteDatabase openDatabase()
{
try
{
boolean b = false;
//得到数据库的完整路径名
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
//将数据库文件从资源文件放到合适地方(资源文件也就是数据库文件放在项目的res下的raw目录中)
//将数据库文件复制到SD卡中 File dir = new File(DATABASE_PATH);
if (!dir.exists())
b = dir.mkdir();
//判断是否存在该文件
if (!(new File(databaseFilename)).exists())
{
//不存在得到数据库输入流对象
InputStream is = activity.getResources().openRawResource(
R.raw.jokebook);
//创建输出流
FileOutputStream fos = new FileOutputStream(databaseFilename);
//将数据输出
byte[] buffer = new byte[8192];
int count = 0;
while ((count = is.read(buffer)) > 0)
{
fos.write(buffer, 0, count);
}
//关闭资源
fos.close();
is.close();
}
//得到SQLDatabase对象
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return null;
}
}
写完这个类之后,就能得到SQLiteDatabase对象,就能对数据库操作了
Before trying this code, please find this line in below code:
private static String DB_NAME ="YourDbName";// Database name
DB_NAME here is the name of your database. It is assumed that you have a copy of the database in the assets folder, so for example if your database name is ordersDB, then the value of DB_NAME will be ordersDB,
private static String DB_NAME ="ordersDB";
Keep the Database in assets folder & then follow below:
DataHelper class:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper
{
private static String TAG = "DataBaseHelper"; // Tag just for the LogCat window
//destination path (location) of our database on device
private static String DB_PATH = "";
private static String DB_NAME ="YourDbName";// Database name
private SQLiteDatabase mDataBase;
private final Context mContext;
public DataBaseHelper(Context context)
{
super(context, DB_NAME, null, 1);// 1? its Database Version
if(android.os.Build.VERSION.SDK_INT >= 4.2){
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
}
else
{
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
}
this.mContext = context;
}
public void createDataBase() throws IOException
{
//If database not exists copy it from the assets
boolean mDataBaseExist = checkDataBase();
if(!mDataBaseExist)
{
this.getReadableDatabase();
this.close();
try
{
//Copy the database from assests
copyDataBase();
Log.e(TAG, "createDatabase database created");
}
catch (IOException mIOException)
{
throw new Error("ErrorCopyingDataBase");
}
}
}
//Check that the database exists here: /data/data/your package/databases/Da Name
private boolean checkDataBase()
{
File dbFile = new File(DB_PATH + DB_NAME);
//Log.v("dbFile", dbFile + " "+ dbFile.exists());
return dbFile.exists();
}
//Copy the database from assets
private void copyDataBase() throws IOException
{
InputStream mInput = mContext.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream mOutput = new FileOutputStream(outFileName);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer))>0)
{
mOutput.write(mBuffer, 0, mLength);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
//Open the database, so we can query it
public boolean openDataBase() throws SQLException
{
String mPath = DB_PATH + DB_NAME;
//Log.v("mPath", mPath);
mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.CREATE_IF_NECESSARY);
//mDataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
return mDataBase != null;
}
@Override
public synchronized void close()
{
if(mDataBase != null)
mDataBase.close();
super.close();
}
}
Write a DataAdapter class like:
import java.io.IOException;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class TestAdapter
{
protected static final String TAG = "DataAdapter";
private final Context mContext;
private SQLiteDatabase mDb;
private DataBaseHelper mDbHelper;
public TestAdapter(Context context)
{
this.mContext = context;
mDbHelper = new DataBaseHelper(mContext);
}
public TestAdapter createDatabase() throws SQLException
{
try
{
mDbHelper.createDataBase();
}
catch (IOException mIOException)
{
Log.e(TAG, mIOException.toString() + " UnableToCreateDatabase");
throw new Error("UnableToCreateDatabase");
}
return this;
}
public TestAdapter open() throws SQLException
{
try
{
mDbHelper.openDataBase();
mDbHelper.close();
mDb = mDbHelper.getReadableDatabase();
}
catch (SQLException mSQLException)
{
Log.e(TAG, "open >>"+ mSQLException.toString());
throw mSQLException;
}
return this;
}
public void close()
{
mDbHelper.close();
}
public Cursor getTestData()
{
try
{
String sql ="SELECT * FROM myTable";
Cursor mCur = mDb.rawQuery(sql, null);
if (mCur!=null)
{
mCur.moveToNext();
}
return mCur;
}
catch (SQLException mSQLException)
{
Log.e(TAG, "getTestData >>"+ mSQLException.toString());
throw mSQLException;
}
}
}
Now you can use it like:
TestAdapter mDbHelper = new TestAdapter(urContext);
mDbHelper.createDatabase();
mDbHelper.open();
Cursor testdata = mDbHelper.getTestData();
mDbHelper.close();
NOTE:
For Jellybean 4.2 change:
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
to:
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
in the DataHelper class this code will work on JB 4.2 multi users.
使用SQLiteOpenHelper的好处就是随着你应用的卸载数据库也一同卸载的,如果是拷入Sdcard的话还得代码操作。。。
如果你放在res中是找不到的 去搜个关于操作SQLiteOpenHelper的小DEMO.
如果你是通过SQLiterOpenHelper创建的应该在Data\data\你的包名里面的database里面