【发布时间】:2015-11-25 16:29:54
【问题描述】:
我正在尝试通过附加 QtSQl 数据库的新数据来更新表列。我需要通过附加新数据来更新列imgpath。
下面是代码,但总是失败,可能是什么问题?
QSqlQuery query(db);
query.exec("create table table1 (id integer primary key autoincrement, time varchar(20), imgpath varchar(20))");
query.exec("insert into table1 values(NULL,'00:15:25','img0.jpg')");
query.exec("insert into table1 values(NULL,'00:15:25','img1.jpg')");
bool up = query.exec("update table1 set imgpath=concat(';newImage.jpg',imgpath) where ID=1");
if(up==false)
qDebug()<<"Update failed";
更新:
完整代码:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("./newDB");
db.open();
QSqlQuery query(db);
query.exec("create table table1 (id integer primary key autoincrement, time varchar(20), imgpath varchar(20))");
query.exec("insert into table1 values(NULL,'00:15:25','img0.jpg')");
query.exec("insert into table1 values(NULL,'00:15:25','img1.jpg')");
//bool up = query.exec("update table1 set imgpath='newimage.jpg',time='' where ID=1");
bool up = query.exec("update table1 set imgpath=concat(';newImage.jpg',imgpath)");
if(up==false){
qDebug()<<"Update failed";
qDebug() << db.lastError();
}
query.exec("SELECT * FROM table1 limit 100");
QVector<QStringList> lst;
while (query.next())
{
QSqlRecord record = query.record();
QStringList tmp;
for(int i=0; i < record.count(); i++)
{
tmp << record.value(i).toString();
}
lst.append(tmp);
}
foreach (const QStringList &var, lst) {
qDebug() << var;
}
【问题讨论】:
-
报错是什么。您的查询看起来不错。我在测试数据库上运行它们,它们都是正确的。
-
嗨,感谢您的评论,代码
qDebug() << db.lastError();给我输出QSqlError("", "", "")似乎没有错误打印。 -
更新后表没有变化?您有一条 id == 1 的记录?
-
是的,我有 id=1 的记录,我会发布完整的代码。
-
这是mysql还是sqlite?你的代码是
QSqlDatabase::addDatabase("QSQLITE")。