只需使用:
SQLiteDatabase.openDatabase(DB_FULL_PATH, null, SQLiteDatabase.OPEN_READONLY);
DB_FULL_PATH可以是您的SD卡路径,例如/sdcard/mydatabase.db。
编辑:
这是我在应用程序中调用以访问数据库的方法...
private static DBUtil dbHelper = null;
public void openDatabase() {
if(dbHelper == null) {
dbHelper = new DBUtil(this.context);
dbHelper.openDataBase(SQLiteDatabase.OPEN_READWRITE);
}
}
public void closeDatabase() {
if(dbHelper != null) {
dbHelper.close();
dbHelper = null;
}
}
这是我正在使用的 db helper 类,实际上是扩展了 SQLiteOpenHelper,因此您仍然可以从这个类中获得您所需的一切。
package com.myapp.android.db;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.myapp.android.MyApp;
import java.io.IOException;
public class DBUtil extends SQLiteOpenHelper {
public static String DB_DIRECTORY = null;
public static String DB_NAME = null;
public static String DB_FULL_PATH = null;
static {
DB_DIRECTORY = MyApp.DATA_REPOSITORY_URI + "/myapp/db/";
DB_NAME = "mydatabase.db";
DB_FULL_PATH = DB_DIRECTORY + DB_NAME;
}
private SQLiteDatabase myDataBase;
public DBUtil(Context context) {
super(context, DB_NAME, null, 1);
try {
this.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
}
public void createDataBase() throws IOException {
if (!checkDataBase()) this.getWritableDatabase();
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
public void openDataBase(int mode) throws SQLException {
try {
myDataBase = SQLiteDatabase.openDatabase(DB_FULL_PATH, null, mode);
} catch(IllegalStateException e) {
Log.d(MyApp.APP, "Database non-closed. Reopening.");
myDataBase = SQLiteDatabase.openDatabase(DB_FULL_PATH, null, mode);
}
}
public void openDataBase() throws SQLException {
openDataBase(SQLiteDatabase.OPEN_READWRITE);
}
public SQLiteDatabase getDb() {
return myDataBase;
}
@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) {
}
}