我正在写一个程序。在某些地方,我想在我的本地数据库中插入一些值。但是如果插入后检查数据库是空的。这是代码
LeaderBase sqh = new LeaderBase(this);
SQLiteDatabase sqdb = null;
if (checkDataBase()){
sqdb = SQLiteDatabase.openDatabase("/data/data/com.example.test7/databases/leader_database.db", null, 0);
}
else{
}
sqdb = sqh.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(LeaderBase.USERNAME, String.valueOf(nameRes));
cv.put(LeaderBase.USERMONEY, moneyRes);
cv.put(LeaderBase.USERTIME, timeRes);
cv.put(LeaderBase.UGAMETYPE, gtype);
sqdb.insert(LeaderBase.TABLE_NAME, null, cv);
Cursor cursor2 = sqdb.query(LeaderBase.TABLE_NAME, new String[] {
LeaderBase._ID, LeaderBase.USERNAME },
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
int check_count = cursor2.getCount();
sqdb.close();
sqh.close();
LeaderBase类的代码:
public class LeaderBase extends SQLiteOpenHelper implements BaseColumns {
private static final String DATABASE_NAME = "leader_database.db";
private static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "leader_board";
public static final String UID = "_id";
public static final String USERNAME = "username";
public static final String USERMONEY = "usermoney";
public static final String USERTIME = "usertime";
public static final String UGAMETYPE = "ugametype";
private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ USERNAME + " VARCHAR(255),"
+ USERMONEY + " BIGINT,"
+ USERTIME + "INT,"
+ UGAMETYPE + "INT"+
");";
private static final String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS "
+ TABLE_NAME;
public LeaderBase(Context context) {
// TODO Auto-generated constructor stub
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
问题是如果我检查值check_count则为零。数据库是空的。 有什么问题?
感谢所有答案!
答案 0 :(得分:2)
我相信您会遇到异常,因为您忘记在列的后面添加一个空格
+ USERTIME + "INT,"+ UGAMETYPE + "INT"+
我建议您使用以下行
更新该行private static final String SQL_CREATE_ENTRIES = "CREATE TABLE "
+ TABLE_NAME + " (" + UID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ USERNAME + " VARCHAR(255),"
+ USERMONEY + " BIGINT,"
+ USERTIME + " INT,"
+ UGAMETYPE + " INT"+");";
注意:执行此更改后,只需从设备/模拟器中删除旧应用程序,然后重试。这背后的实际原因是您的create table查询将在onCreate()
方法中执行。所以要调用它,你必须卸载以前的应用程序。