三部配置:
1.首先QT5.1验证数据库驱动,代码如下:
QApplication a(argc, argv);
MainWindow w;
w.show();
qDebug()<<"Available drivers:";
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug() <<"\r" << driver;
QT5.1默认情况下应为:"QSQLITE"
"QODBC"
"QODBC3"
"QPSQL"
"QPSQL7"
没有包含QMYSQL,可以到http://download.csdn.net/download/ljasdf123/5835615下载qt5.1.0的mingw的mysql驱动
解压4个文件安装到你的QT目录下F:\Qt\5.1.0\mingw48_32\plugins\sqldrivers 具体格式安自己的定;
2.下免安装MYSQL-5.1.6环境搭建
解压,然后如下配置: 拷贝 my-huge.ini 另存为my.ini文件 设定字符集为utf8 (切忌不是utf-8)
自己按照解压目录配置环境变量到bin目录下;
D:\mysql\bin>mysqladmin -u root password 新密码
安装到系统服务中 D:\mysql\bin> mysqld --install MySQL5.1.6 --defaults-file=D:\myjweb\mysql\my.ini
启动mysql服务 D:\mysql\bin> NET START MySQL5.1.6
登陆MySQL D:\mysql -u root -p
Enter password: *********
停止mysql服务 D:\mysql\bin> NET STOP MySQL5.1.6
3.测试:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setDatabaseName("test"); //该sql库中有个默认的test 具体可以登陆cmd登陆mysql用show databases;命令看
db.setUserName("root");
db.setPassword("新密码");
bool ok = db.open();
if (ok == true)
{qDebug()<< "=========== connect ok =============";
}else{}
//db.close() //注释不关闭连接 可以用cmd登陆数据库用mysql> show processlist;看连接数 +----+------+-----------------+-------+---------+------+-------+------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+------+-----------------+-------+---------+------+-------+------------------+ | 5 | root | localhost:11948 | mysql | Query | 0 | NULL | show processlist | <-------------cmd的连接 | 9 | root | localhost:13207 | test | Sleep | 4 | | NULL |<------------- QT程序的连接 +----+------+-----------------+-------+---------+------+-------+------------------+ 2 rows in set (0.00 sec) mysql>