//创建数据库,如果已存在则打开 SQLiteDatabase db = getApplicationContext().openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null); //删除数据库 getApplicationContext().deleteDatabase("test.db");
管理类
openDatabase : 打开指定路径的数据库import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class TestDBHelper extends SQLiteOpenHelper { private static final String TAG = "TestDBHelper"; private static final String DB_NAME = "test.mDB"; private static final int DB_VERSION = 1; private static TestDBHelper mHelper = null; private SQLiteDatabase mDB = null; private TestDBHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } private TestDBHelper(Context context, int version) { super(context, DB_NAME, null, version); } public static TestDBHelper getInstance(Context context, int version) { if (version > 0 && mHelper == null) { mHelper = new TestDBHelper(context, version); } else if (mHelper == null) { mHelper = new TestDBHelper(context); } return mHelper; } public SQLiteDatabase openReadLink() { Log.d(TAG, "openReadLink"); if (mDB == null || mDB.isOpen() != true) { mDB = mHelper.getReadableDatabase(); } return mDB; } public SQLiteDatabase openLink() { Log.d(TAG, "openLink"); if (mDB == null || mDB.isOpen() != true) { mDB = mHelper.getWritableDatabase(); } return mDB; } public void closeLink() { Log.d(TAG, "closeLink"); if (mDB != null && mDB.isOpen() == true) { mDB.close(); mDB = null; } } public String getDBName() { if (mHelper != null) { return mHelper.getDatabaseName(); } else { return DB_NAME; } } @Override public void onCreate(SQLiteDatabase db) { Log.d(TAG, "onCreate"); String create_sql = "CREATE TABLE IF NOT EXISTS person (" + "_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ," + "name VARCHAR NOT NULL," + "age INTEGER NOT NULL" + ")"; Log.d(TAG, "create_sql:" + create_sql); db.execSQL(create_sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.d(TAG, "onUpgrade"); if (newVersion == 10) { String alter_sql = "ALTER TABLE person ADD COLUMN company VARCHAR"; Log.d(TAG, "alter_sql:" + alter_sql); db.execSQL(alter_sql); } } }