SQLite参数数量不匹配问题求助:员工信息存入数据库失败
问题原因及修复方案
核心错误原因
你遇到的Parameter count mismatch错误,是因为SQL语句里没有使用占位符,却调用了addBindValue绑定参数,导致数据库驱动认为你需要传递参数,但SQL里没有对应占位符,参数数量不匹配。另外代码还存在重复执行exec()的问题。
修复后的代码
void oviewsettings::on_pushButton_clicked() { QString Registration, Name, Surname, Access, Phone, Email, Username, Password; Registration = ui->lineEdit_usermanagement_Registration->text(); Name = ui->lineEdit_usermanagement_Name->text(); Surname = ui->lineEdit_usermanagement_Surname->text(); Access = ui->lineEdit_usermanagement_Access->text(); Phone = ui->lineEdit_usermanagement_Phone->text(); Email = ui->lineEdit_usermanagement_Email->text(); Username = ui->lineEdit_usermanagement_Username->text(); Password = ui->lineEdit_usermanagement_Password->text(); OViewMain conn; if(!conn.connOpen()){ qDebug()<<"Failed to open the database"; return; } QSqlQuery qry; // 使用占位符代替字符串拼接,避免SQL注入,同时匹配绑定的参数 qry.prepare("INSERT INTO employeeinfo(Registration,Name,Surname,Access,Phone,Email,Username,Password) VALUES (:Registration, :Name, :Surname, :Access, :Phone, :Email, :Username, :Password)"); // 绑定实际变量值到占位符 qry.bindValue(":Registration", Registration); qry.bindValue(":Name", Name); qry.bindValue(":Surname", Surname); qry.bindValue(":Access", Access); qry.bindValue(":Phone", Phone); qry.bindValue(":Email", Email); qry.bindValue(":Username", Username); qry.bindValue(":Password", Password); // 只执行一次exec(),并判断执行结果 if(qry.exec()) { QMessageBox::critical(this,tr("Save"),tr("Database Updated, Saved")); conn.connClose(); } else { QMessageBox::critical(this,tr("Error"),qry.lastError().text()); conn.connClose(); // 失败也要关闭数据库连接 } }
关键修复点说明
- 正确使用参数绑定:SQL语句中用
:占位符代替直接字符串拼接,然后通过bindValue将变量值绑定到对应占位符,既解决参数不匹配问题,又避免SQL注入风险。 - 移除重复的
exec()调用:原代码先执行了一次qry.exec(),之后又在if判断里执行一次,会导致重复插入且查询状态异常,只保留一次执行并判断结果即可。 - 失败时关闭数据库连接:原代码只在成功时关闭连接,失败时未处理,补充后避免连接泄漏。
内容的提问来源于stack exchange,提问作者Pixal
相关产品推荐
相关产品推荐

