void AddDialog::itemChanged(QTableWidgetItem current,QTableWidgetItem previous){
if(previous != NULL){
int index = previous->row();
int column =previous->column();
QSqlQuery query(db);
QString sqlStr = "select * from ";
QString table = ui->TableCombo->itemText(ui->TableCombo->currentIndex());
sqlStr += table;
QMessageBox box;
if(!query.exec(sqlStr)){
box.setText(query.lastError().text());
box.exec();
return ;
}
query.seek(index);
query.record().setValue(column,previous->text());
}
}
//这里的db是QDatabase类型的数据库对象 已经确认数据库正确连接,而且可以使用query.exec()执行更新的SQL语句没有问题.为什么setValue会没有效果
在执行完 setValue 函数之后,你需要调用 QSqlQuery 的 prepare 函数来生成更新数据库中某条记录的SQL语句,然后再调用 exec 函数来执行这条SQL语句。例如:
query.prepare(
"UPDATE " + table + " SET column = :newValue WHERE id = :id"
);
query.bindValue(":newValue", previous->text());
query.bindValue(":id", query.value(0));
if (!query.exec()) {
// error handling
}
你也可以使用 QSqlTableModel 类来简化对数据库的操作,它提供了更多的函数来方便地更新数据库中的记录。
此外,你还可以检查一下 QSqlQuery 的 numRowsAffected 函数的返回值,以确定是否有记录被更新。