Qt学习(十):QT连接mysql(增加、删除、遍历)
生活随笔
收集整理的這篇文章主要介紹了
Qt学习(十):QT连接mysql(增加、删除、遍历)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
知識點
- Qt連接數據庫
- 數據庫的插入+刪除+遍歷
- 數據庫的批量插入
完整項目github地址:
結果演示
問題解決
連接數據庫后,執行命令以后,數據庫里面沒有相應的結果,打印后錯誤是: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"); //數據庫服務器IPdb.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();
private:
Ui::Widget *ui;
};
#endif // WIDGET_H
總結
以上是生活随笔為你收集整理的Qt学习(十):QT连接mysql(增加、删除、遍历)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt学习(九):QT中使用线程
- 下一篇: Qt学习(十一):QT设置静态数据库