一。Navicat for MySQL
新建连接->MySQL
二。拷贝dll库和lib文件
1.将D:\software\mysql-5.6.43-winx64\lib下libmysql.dll和libmysqld.dll拷贝到 D:\Qt\Qt5.8.0\5.8\msvc2015_64\bin
2.将D:\software\mysql-5.6.43-winx64\lib下libmysql.lib和libmysqld.lib拷贝到 D:\Qt\Qt5.8.0\5.8\msvc2015_64\lib
三。vs属性设置
在解决方案工程属性中
1.C/C++->常规->附加包含目录 中添加$(QTDIR)\include\QtSql
2.链接器->输入->附加依赖库 中添加Qt5Sqld.lib和Qt5Sql.lib
四。编码
#include "QtGuiApplication4.h"
#include
#include
#include "QtGuiClass.h"
#include "MyWebQt.h"
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QSqlDatabase db;
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug() << "\t " << driver;
qDebug() << "End";
//QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
if (QSqlDatabase::contains("test"))
{
}
else
{
db = QSqlDatabase::addDatabase("QMYSQL"); //, "localhost@3306"
db.setHostName("localhost"); //数据库主机名
db.setDatabaseName("test"); //数据库名
db.setUserName("root"); //数据库用户名
db.setPassword(""); //数据库密码
}
bool bisOpenn = db.open(); //打开数据库连接 if (db.open()) qDebug("table is error"); QSqlQuery query; return a.exec(); 五。在Navicat for MySQL中可以看到如下
qDebug()<<"bisOpenn="<
{
QMessageBox::warning(NULL, QStringLiteral("提示"), "open ok", QMessageBox::Yes);
}
else
{
QMessageBox::warning(NULL, QStringLiteral("提示"), "open failed", QMessageBox::Yes);
}
QSqlQuery sql_query(db);
bool buscess = sql_query.exec("create table person (id int primary key, firstname varchar(20), lastname varchar(20))");
sql_query.exec("insert into person values(101, 'Danny', 'Young')");
sql_query.exec("insert into person values(102, 'Christine', 'Holand')");
sql_query.exec("insert into person values(103, 'Lars', 'Gordon')");
sql_query.exec("insert into person values(104, 'Roberto', 'Robitaille')");
sql_query.exec("insert into person values(105, 'Maria', 'Papadopoulos')");
if (!buscess)
{
}
else
{
qDebug("table is sucess");
}
query.exec("select * from person");
while (query.next())
{
qDebug() << query.value(0).toInt() << query.value(1).toString() << query.value(2).toString();
}
}