【发布时间】:2014-05-28 08:33:59
【问题描述】:
我在我的 Android 应用上查询 SQLite 数据库时遇到问题。我使用this tutorial 来设置我的数据库助手类。
我做了一个简单的查询函数:
public Cursor queryDB(String Query,String[] args){
Cursor cursor = myDataBase.rawQuery(Query, args);
return cursor;
然后我这样称呼它:
String[] testarg = {"Denver Bake"};
myDataBase.getReadableDatabase();
Cursor results = myDataBase.queryDB("SELECT * FROM Recipes WHERE r_name = ?", testarg);
我得到的错误是:
E/AndroidRuntime(30483): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dbtest/com.example.dbtest.MainActivity}: android.database.sqlite.SQLiteException: no such table: Recipes: , while compiling: SELECT * FROM Recipes WHERE r_name = ?
我知道Recipes 表确实存在于我的数据库中,因为它出现在本教程的SQLite 数据库浏览器中。我已经尝试了教程 cmets 中的一些建议,但我仍然遇到同样的错误,我不确定现在该怎么做。
先谢谢了。
这是我的创作
public void createDataBase() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
}else{
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
这是我的复制代码:
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
最后,我的资产文件夹中确实有我的数据库。错误信息告诉我数据库中的表不存在。
【问题讨论】:
-
发布您的创建表查询。
-
你必须在浏览器中创建你自己的sqlite数据库。并将这个数据库复制到你项目的assets文件夹中。
-
阅读错误信息!正如它(和@dipali)所说,您没有创建数据库。以下来自@krishanDhamat 的答案显示了您应该做什么:使用 SQLiteOpenHelper。您需要在其他地方阅读,以了解原因...
-
显然,您没有正确复制数据库。显示从资产文件夹复制数据库的代码。