序
最近在Ubuntu15.04下做一个Linux-服务器-客户端通信项目,用到MySQL数据库。开始的时候,在数据库链接时遇到障碍,查找资料解决。
特此记录,分享于此。
环境配置
系统:Ubuntu 15.04
IDE:QtCreator
数据库:MySQL (在软件中心,安装服务器端以及客户端)
MySQL驱动:Qt5链接mysql最新驱动网址
如果,刚安装了mysql并没有设置初始root密码,则使用以下步骤设置,若已经设置,则可跳过该步骤:
yangrui@ubuntu:~$ mysql -u root
//出现以下内容
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.25-0ubuntu0.15.04.1 (Ubuntu)
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
//设置密码
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('123456');
Query OK, 0 rows affected (0.07 sec)
//建库
mysql> create database EasyChat
链接测试
新建控制台程序:
#include <QCoreApplication>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qDebug()<<"available drivers:";
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug()<<driver;
QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setPort(3306);
db.setDatabaseName("EasyChat");
db.setUserName("root");
db.setPassword("123456");
if(!db.open()){
qDebug()<<"Unable to open database";
}else{
qDebug()<<"Database connection established";
}
return a.exec();
}
运行,会出现一堆
undefined reference to `QSqlDatabase::drivers()'
...
之类的错误!
此时只需要,在.pro文件中,添加下面一句:
QT += sql
再次运行:
available drivers:
"QSQLITE"
"QMYSQL"
"QMYSQL3"
Database connection established
成功!