1、将MySQL安装目录下的libmysql.dll拷贝到Qt安装目录下的bin目录中。
2、准备数据库和数据表如下:
3、编写如下代码:
#-------------------------------------------------
#
# Project created by QtCreator 2016-07-15T17:56:50
#
#-------------------------------------------------QT += core gui
QT +=sqlgreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsTARGET = Test03
TEMPLATE = appSOURCES += main.cpp\mainwindow.cppHEADERS += mainwindow.hFORMS += mainwindow.ui
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>MainWindow::MainWindow(QWidget *parent) :QMainWindow(parent),ui(new Ui::MainWindow)
{ui->setupUi(this);ui->pushButton->setText("连接数据库");
}MainWindow::~MainWindow()
{delete ui;
}void MainWindow::on_pushButton_clicked()
{QSqlDatabase db;if(QSqlDatabase::contains("employeedb"))db = QSqlDatabase::database("employeedb");elsedb = QSqlDatabase::addDatabase("QMYSQL", "employeedb");db.setHostName("localhost");db.setDatabaseName("employeedb"); // 数据库名称db.setUserName("root"); // 用户名db.setPassword("226"); // 密码bool ok = db.open(); // 尝试连接数据库if(ok){QSqlQuery myquery("select * from employeetb",db);while(myquery.next()){QString name=myquery.value(0).toString().trimmed();qDebug()<<name;}}db.close();
}
4、运行效果如下:
点击连接数据库,应用程序输出如下: