linux qt连接mysql数据库
时间: 2023-08-07 14:08:31 浏览: 344
要在Linux上使用Qt连接MySQL数据库,需要完成以下步骤:
1. 安装MySQL服务器和Qt库。
2. 在Qt项目中添加mysql驱动器。在.pro文件中添加以下代码:
```
QT += sql
QT += mysql
INCLUDEPATH += /usr/include/mysql
LIBS += -L/usr/lib/x86_64-linux-gnu/ -lmysqlclient
```
3. 在Qt代码中打开数据库连接。以下是一个示例:
```
#include <QCoreApplication>
#include <QtSql>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("mydatabase");
db.setUserName("myusername");
db.setPassword("mypassword");
if (db.open()) {
qDebug() << "Database connected!";
} else {
qDebug() << "Database NOT connected!";
}
return a.exec();
}
```
其中,"localhost"是MySQL服务器的主机名,"mydatabase"是要连接的数据库名称,"myusername"和"mypassword"是要用于连接的用户名和密码。
4. 在Qt代码中执行SQL查询。以下是一个示例:
```
QSqlQuery query;
query.exec("SELECT * FROM mytable");
while (query.next()) {
QString name = query.value(0).toString();
int age = query.value(1).toInt();
qDebug() << name << age;
}
```
在上面的示例中,查询了"mytable"表中的所有数据,并将结果输出到控制台。
希望这些步骤对你有所帮助!
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20210720083447.png)