我正在使用 SQLite 数据库来存储一些字符串。当我第一次启动应用程序时,我正在使用此代码添加这些字符串。
DatabaseHandler db = new DatabaseHandler(this);
db.addProducts(//lot of strings appended to make a single String);
db.close();
数据库处理程序是:
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "my_db";
private static final String TABLE_NAME = "products";
private static final String KEY_NAME = "pname";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_PRODUCTS_TABLE = "CREATE TABLE " + TABLE_NAME + "("
+ KEY_NAME + " TEXT" + ")";
db.execSQL(CREATE_PRODUCTS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public void addProducts(String product_name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, product_name); // Product Name
db.insert(TABLE_NAME, null, values);
db.close();
}
public String getProducts() {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_NAME;
Cursor cursor = db.rawQuery(selectQuery, null);
String s = "default";
if (cursor.moveToFirst()) {
int n = cursor.getCount();
s = cursor.getString(0);
}
cursor.close();
return s;
}
}
问题是如果我不检查表是否products
存在,我会在db.addProducts("");
每次启动应用程序时调用。并且游标计数每次都会增加1
,最终会说need to extend db
类似的话。我如何检查表是否已经存在?
我只能找到这个How to check if database exists
::
public static boolean checkDataBase(String DB_FULL_PATH) {
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
checkDB.close();
} catch (SQLiteException e) {
// database doesn't exist yet.
}
return checkDB != null ? true : false;
}
在这里,我被困住了。如何获取数据库的路径?
此外,如果我检查表是否存在而不是数据库,这将很有用。
谢谢你