【发布时间】:2021-12-02 02:29:16
【问题描述】:
此代码可以成功地将 .csv 文件中的整数值插入 SQLite 数据库。但是,当值是字符串时。它不插入字符串值。请帮忙。
QFile f(csvFile);
if(f.open (QIODevice::ReadOnly)){
QSqlQuery que;
QTextStream ts (&f);
//Travel through the csv file "excel.csv"
while(!ts.atEnd()){
QString req = "INSERT INTO main VALUES(";
QStringList line = ts.readLine().split(',');
for(int i=0; i<line .length ();++i){
req.append(line.at(i));
req.append(",");
}
req.chop(1); // remove the trailing comma
req.append(");"); // close the "VALUES([...]" with a ");"
que.exec(req);
qDebug()<<req;
que.lastError();
}
qDebug()
"插入主值(1,2,3);" "插入主值(a,b,c);"
【问题讨论】:
-
"INSERT INTO main VALUES(a,b,c);"需要引用文本。 -
为避免此类错误,最重要的是避免任何 SQL 注入风险,切勿使用变量值构建 SQL 语句,而是使用准备好的语句。我不知道 Qt 如何处理 SQLite 准备好的语句,但肯定有一种方法,可能比你的代码更简单。