Qt学习(十):QT连接mysql(增加、删除、遍历)
知识点Qt连接数据库数据库的插入+删除+遍历数据库的批量插入完整项目github地址:https://github.com/taw19960426/Qt_study/tree/main/DataBase结果演示问题解决连接数据库后,执行命令以后,数据库里面没有相应的结果,打印后错误是:QSqlError(“2036”, “QMYSQL3: Unable to bind value”, "Using
·
知识点
- Qt连接数据库
- 数据库的插入+删除+遍历
- 数据库的批量插入
完整项目github地址:
https://github.com/taw19960426/Qt_study/tree/main/DataBase
结果演示
问题解决
连接数据库后,执行命令以后,数据库里面没有相应的结果,打印后错误是:QSqlError(“2036”, “QMYSQL3: Unable to bind value”, "Using unsupported buffer
原因:
之前我安装的libmysql.dll与版本不兼容
解决办法:将上面github项目文件下的libmysql.dll复制到Qt的安装目录bin文件夹下
widget.cpp
#include "widget.h"
#include "ui_widget.h"
#include <QSqlDatabase>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariantList>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//打印Qt支持的数据库驱动
qDebug() << QSqlDatabase::drivers();
//添加MySql数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1"); //数据库服务器IP
db.setUserName("root"); //数据库用户名
db.setPassword("qaz12580"); //密码
db.setDatabaseName("info"); //使用哪个数据库
//打开数据库
if( !db.open() ) //数据库打开失败
{
QMessageBox::warning(this, "错误", db.lastError().text());
return;
}
//创建表
QSqlQuery query;
// query.exec("create table student(id int primary key auto_increment, name varchar(255), age int, score int);");
// //插入
// //query.exec("insert into student(id, name, age, score) values(1, 'xiaoMing', 18, 59);");
// //批量插入
// //oracle风格
// //占位符 : + 自定义名字
// query.prepare("insert into student(name, age, score) values(:name, :age, :score)");
// //给字段设置内容 list
// QVariantList nameList;
// nameList << "xiaod" << "xiaoe" << "xiaof";
// QVariantList ageList;
// ageList << 13 << 16 << 45;
// QVariantList scoreList;
// scoreList << 85 << 16 << 66;
// //给字段绑定
// query.bindValue(":name",nameList);
// query.bindValue(":age",ageList);
// query.bindValue(":score",scoreList);
// //执行预处理命令
// if(!query.execBatch()){
// qDebug() << query.lastError();
// }
//遍历数据库
query.exec("select * from student");
while(query.next()){
//一行一行遍历
qDebug() << query.value(0).toInt()
<< query.value(1).toString()
<< query.value("age").toInt()
<< query.value("score").toInt();
}
}
Widget::~Widget()
{
delete ui;
}
void Widget::on_buttonDel_clicked()
{
//获取编辑器内容
QString name=ui->lineEdit->text();
QString del=QString("delete from student where name = '%1';").arg(name);
//开启一个事务
QSqlDatabase::database().transaction();
QSqlQuery query;
query.exec(del);
}
void Widget::on_buttonQueDing_clicked()
{
//确定删除
QSqlDatabase::database().commit();
}
void Widget::on_buttonQuXiao_clicked()
{
//撤销删除
QSqlDatabase::database().rollback();
}
widget.h
#ifndef WIDGET_H
#define WIDGET_H
#include
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
private slots:
void on_buttonDel_clicked();
void on_buttonQueDing_clicked();
void on_buttonQuXiao_clicked();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
更多推荐
已为社区贡献2条内容
所有评论(0)