【问题标题】:SQLITE update query failsSQLITE 更新查询失败
【发布时间】: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() &lt;&lt; db.lastError(); 给我输出 QSqlError("", "", "") 似乎没有错误打印。
  • 更新后表没有变化?您有一条 id == 1 的记录?
  • 是的,我有 id=1 的记录,我会发布完整的代码。
  • 这是mysql还是sqlite?你的代码是QSqlDatabase::addDatabase("QSQLITE")

标签: sql qt sqlite qtsql


【解决方案1】:

SQLite 不支持 concat 函数。如果你删除

imgpath=concat(';newImage.jpg',imgpath)");

并用标准的 colName='Value' 语法替换它我打赌一切都会开始工作。如果您想将文本附加到当前值,您应该能够使用类似以下语法的方式来完成:

bool up = query.exec("update table1 set imgpath=';newImage.jpg'||imgpath");

【讨论】:

    猜你喜欢
    • 2021-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多