我正在尝试插入调用以在sqlite代码中向我的表中添加行, 每次插入返回1,并且在插入行之后我检查该行是否插入且无法找到。
这是我的代码:
创建表格
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
// create table artists
String createTableStatement1 = "CREATE TABLE " + TABLE_ARTISTS +" ("+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE , "
+ KEY_ARTIST_NAME + " TEXT UNIQUE , " + KEY_ARTIST_IMAGE + " BLOB, " + KEY_ARTIST_JSON + " TEXT, "
+ KEY_ARTIST_DATE + " DATETIME DEFAULT (datetime('now')), " + KEY_ARTIST_FLAG + " INTEGER NOT NULL DEFAULT 1);";
db.execSQL(createTableStatement1);
//creat table users
String createTableStatement2 = "CREATE TABLE "+ TABLE_USERS + " ("+ KEY_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, "
+ KEY_PROFILE_ID + " TEXT UNIQUE, " + KEY_PROFILE_JSON + " TEXT, "+ KEY_PROFILE_IMAGE + " BLOB, " + KEY_PROFILE_FLAG
+ " INTEGER NOT NULL);";
db.execSQL(createTableStatement2);
}
升级表格
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_ARTISTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
// Create tables again
onCreate(db);
}
插入用户行
public void insertUserToDB(User user)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_PROFILE_FLAG, user.getProfile_flag());
values.put(KEY_PROFILE_IMAGE, user.getProfileImageByteArray());
values.put(KEY_PROFILE_JSON, user.getProfile_json());
values.put(KEY_PROFILE_ID, user.getProfile_id());
db.beginTransaction();
long result = db.insertOrThrow(TABLE_USERS, null, values);
db.endTransaction();
db.close();
}
检查数据库中的用户
public boolean isUserInDB(String profileID)
{
SQLiteDatabase db = this.getReadableDatabase();
db.beginTransaction();
String sqlStatement = "SELECT * FROM "+ TABLE_USERS +" WHERE " + TABLE_USERS + "."+ KEY_PROFILE_ID +
"=" + "\""+ profileID + "\"";
Cursor cursor = db.rawQuery(sqlStatement, null);
boolean exists = ((cursor.getCount())!=0);
cursor.close();
db.endTransaction();
db.close();
return exists;
}
任何想法?
答案 0 :(得分:3)
您需要致电setTransactionSuccessful()
让endTransaction()
应用您的更改。
答案 1 :(得分:2)
db.beginTransaction();
try {
...
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
db.setTransactionSuccessful();
方法是最重要的部分,因为它确认了整个交易的保存。如果没有此调用,您的数据库将不会发生任何变化。