使用prepared语句和sqlite事务语句

Using prepared statement with sqlite transaction statement

本文关键字:语句 事务 sqlite 使用 prepared      更新时间:2023-10-16

我试图在sqlite中插入大量数据,为了获得性能,我使用transaction语句。我的代码如下所示:CSV解析器;

   query.exec("BEGIN TRANSACTION;");
   while (!file.atEnd())
    {
           line = file.readLine();
           if (line == "")
                  continue;
            parser << line.toStdString(); // Feed the line to the parser
                // Now extract the columns from the line
            parser >> sCol1 >> sCol2 >> sCol3 >> sCol4;
            // Method one to insert data
            sqlQuery = "INSERT INTO Person(phone, name, firstname, lastname) VALUES (" 
                         "'" + QString(sCol1.c_str()) + 
                         "','" + QString(sCol2.c_str()) + 
                         "','" + QString(sCol4.c_str()) + 
                         "','" + QString(sCol3.c_str()) + "')";
            //query.exec(sqlQuery);
            // Method two to insert data
             query.prepare("INSERT INTO Person(phone, name, firstname, lastname) VALUES (:phone, :name, firstname, :lastname");
             query.bindValue(":phone", QString(sCol1.c_str()));
             query.bindValue(":name", QString(sCol2.c_str()));
             query.bindValue(":firstname", QString(sCol4.c_str()));
             query.bindValue(":lastname", QString(sCol3.c_str()));
             query.exec();
             cout << query.lastError().text().toStdString();
      }
   query.exec("END TRANSACTION;");  

如果我使用第一种方法,插入的数据会很好,但如果文本包含像"这样的charcarter,则稍后可能会出现问题。为了避免这种情况,我切换到准备好的语句,这是一个新问题,没有插入数据。我看到的唯一错误:

参数计数不匹配参数计数不一致参数计数不匹配参数计数不匹配参数数目不匹配参数计数不匹配参数计数不匹配我在这里失踪了吗?

我想知道这是否是原因:

query.prepare("INSERT INTO Person(phone, name, firstname, lastname)
    VALUES (:phone, :name, firstname, :lastname");
                                              ^^^
         missing close paren inside the string^^^