QT连接MySql

1. 安装QT MySQL驱动

将驱动放置目录:

QT连接MySql

2. 数据库表

QT连接MySql

3. 访问

添加sql

QT连接MySql

main.h
#include <QtSql>

private:
    QSqlDatabase db;
private slots:
    void showDatabaseDataSlot();


//构造
QObject::connect(ui->listButton, SIGNAL(clicked()), this, SLOT(showDatabaseDataSlot()));



void MainWindow::showDatabaseDataSlot()
{
    //连接
    this->db = QSqlDatabase::addDatabase("QMYSQL");  
    this->db.setHostName("localhost");
    this->db.setUserName("root");
    this->db.setPassword("123456");
    this->db.setDatabaseName("student");
    
    bool ok = db.open();
    if (ok)
    {
        qDebug() << "open mysql success";
    }
    else
    {
        qDebug() << "error open mysql" << this->db.lastError()->text();
    }

    //查询
    QsqlQuery query;
    query.exec("select * from information");
    while(query.next())
    {
        int id = query.value(0).toInt();
        QString name = query.value(1).toString();
        QString address= query.value(2).toString();
        QString pickname = query.value(3).toString();

        qDebug() << id << name << address << pickname;
    }
    this->db.close();

    //插入
    QsqlQuery query;
    query.prepare("INSERT INTO information(id, name, address, pickname)"
            "VALUES(:id, :name, :address, :pickname)");
    query.bindValue(":id", 1001);
    query.bindValue(":name", "zzyy");
    query.bindValue(":address", "213213");
    query.bindValue(":pickname", "asdasd");
    bool ok = query.exec();
    if (ok)
    {
       qDebug() << "surcess"; 
    }
    else
    {
        qDebug() << "error message" << query.lastError().text();
    }
}

QT连接MySql

QT连接MySql