我编写了这个简单的Activity来测试Android上的SQLite数据库的编写和读取。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DatabaseHelper db = new DatabaseHelper(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class DatabaseHelper extends SQLiteOpenHelper
{
public DatabaseHelper(Context context) {
super(context, "TestDatabase", null, 3);
getWritableDatabase().rawQuery("INSERT INTO TestTable VALUES ('Apple')", null);
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM TestTable", null);
Log.d("trace", String.valueOf(cursor.moveToFirst()));
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE TestTable (value text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS TestTable");
onCreate(db);
}
}
}
它的主要内容在DatabaseHelper构造函数中,我在其中向TestTable写入一个值,尝试将其返回到游标中,然后记录cursor.moveToFirst()的值(它应该只是{{1}如果光标为空)。它是false
。发生了什么事?
答案 0 :(得分:1)
答案 1 :(得分:0)
1)应该将rawQuery()更改为execSQL,如下面一行:
public DatabaseHelper(Context context) {
super(context, "TestDatabase", null, 3);
getWritableDatabase().execSQL("INSERT INTO TestTable VALUES ('Apple')");
Cursor cursor = getReadableDatabase().rawQuery("SELECT * FROM TestTable", null);
Log.d("trace:", String.valueOf(cursor.moveToFirst()));
}
2)为了确保调用onCreate(),覆盖DatabaseHelper类中的onDowngrade():
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS TestTable");
onCreate(db);
}