gpt4 book ai didi

java - 查询未正确运行 - SQlite Android Studio

转载 作者:行者123 更新时间:2023-12-02 08:46:52 25 4
gpt4 key购买 nike

我有这个函数,应该将数据插入到 SQlite DB 中,如果数据没有插入,则返回 false,但是该函数返回 true,但是当我去检查 .db 文件时,表中没有数据。

public boolean insertData(String name, String emailAddress, String postalAddress, String password, int phoneNumber, String bloodType) {
ContentValues contentValues = new ContentValues();
SQLiteDatabase db = this.getWritableDatabase();

//set data to columns
contentValues.put(COL_2, name);
contentValues.put(COL_3, emailAddress);
contentValues.put(COL_4, postalAddress);
contentValues.put(COL_5, password);
contentValues.put(COL_6, phoneNumber);
contentValues.put(COL_7, bloodType);

//inserts data into db
long result = db.insert(TABLE_NAME, null, contentValues);

//checks to see if data has been inserted correctly
if (result == -1) {
return false;
} else
return true;


}

下图显示表和数据库已正确创建。

database info

最佳答案

您应该像 here 中所述那样调用 #beginTransaction()#setTransactionSuccessful()#endTransaction() .

The changes will be rolled back if any transaction is ended without being marked as clean (by calling setTransactionSuccessful).

public boolean insertData(String name, String emailAddress, String postalAddress, String password, int phoneNumber, String bloodType) {
ContentValues contentValues = new ContentValues();
SQLiteDatabase db = this.getWritableDatabase();

db.beginTransaction();
try {
contentValues.put(COL_2, name);
contentValues.put(COL_3, emailAddress);
contentValues.put(COL_4, postalAddress);
contentValues.put(COL_5, password);
contentValues.put(COL_6, phoneNumber);
contentValues.put(COL_7, bloodType);
long result = db.insert(TABLE_NAME, null, contentValues);
db.setTransactionSuccessful();
return result != -1;
} finally {
db.endTransaction();
}
}

关于java - 查询未正确运行 - SQlite Android Studio,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61016636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com