当前位置:网站首页>【QT】测试Qt是否能连接上数据库
【QT】测试Qt是否能连接上数据库
2022-07-01 23:46:00 【Cappuccino-jay】
第一步:创建一个widget项目
然后给项目文件也就是.pro文件添加QT += sql,如下所示:
第二步:使用 QSqlDatabase
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QSqlDatabase>
#include <QDebug>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = nullptr);
~Widget();
private:
Ui::Widget *ui;
QSqlDatabase db;
};
#endif // WIDGET_H

第三步:连接数据库
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
db = QSqlDatabase::addDatabase("QMYSQL");
//设置ip、端口、名字、密码
db.setHostName("127.0.0.1");
db.setPort(3306);
db.setDatabaseName("mysql");
db.setUserName("root");
db.setPassword("root");
//打开数据库
bool res = db.open();
if(res){
qDebug()<< "connect success";
}
else{
qDebug()<< "connect error";
}
//关闭数据库
db.close();
}
Widget::~Widget()
{
delete ui;
}

第四步:运行程序

边栏推荐
- Material Design组件 - 使用BottomSheet展现扩展内容(一)
- 在代码中使用SqlCommand对象
- Redis RDB snapshot
- Know --matplotlib
- Write some suggestions to current and future doctoral students to sort out and share
- MySQL Replication中并行复制怎么实现
- 2021 RoboCom 世界机器人开发者大赛-高职组初赛
- 【必会】BM41 输出二叉树的右视图【中等+】
- Redis data types and application scenarios
- Windows 7 install MySQL error: 1067
猜你喜欢

2021 RoboCom 世界机器人开发者大赛-高职组初赛

问题随记 —— /usr/bin/perl is needed by MySQL-server-5.1.73-1.glibc23.x86_64

Deep learning | three concepts: epoch, batch, iteration

Commemorate becoming the first dayus200 tripartite demo contributor

.env.xxx 文件,加了常量,卻undefined

使用VB.net将PNG图片转成icon类型图标文件

Redis AOF日志

Redis 主从同步

Postgresql源码(57)HOT更新为什么性能差距那么大?

物联网技术应用属于什么专业分类
随机推荐
Door level modeling - after class exercises
物联网应用技术专业是属于什么类
物联网技术应用属于什么专业分类
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
.env.xxx 文件,加了常量,却undefined
PostgreSQL notes (10) dynamically execute syntax parsing process
What is the difference between memory leak and memory overflow?
Linux基础 —— CentOS7 离线安装 MySQL
Use vb Net to convert PNG pictures into icon type icon files
Know --matplotlib
PostgreSQL source code (57) why is the performance gap so large in hot update?
Notblank and notempty
[must] bm41 output the right view of the binary tree [medium +]
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决
Li Kou today's question -241 Design priorities for operational expressions
Anomaly-Transformer (ICLR 2022 Spotlight)复现过程及问题
Daily three questions 6.30 (2)
Matplotlib common settings
How to display real-time 2D map after rviz is opened
Algolia's search needs are almost closed