当前位置:网站首页>【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;
}
第四步:运行程序
边栏推荐
- TS初次使用、ts类型
- ADO. Net SqlDataAdapter object
- Postgresql随手记(10)动态执行EXECUTING语法解析过程
- SQL optimization
- 攻防演练复盘
- The essence of software architecture
- from pip._ internal. cli. main import main ModuleNotFoundError: No module named ‘pip‘
- Why is PHP called hypertext preprocessor
- Why does blocprovider feel similar to provider?
- Zero foundation tutorial of Internet of things development
猜你喜欢
第六章 数据流建模
使用 pair 做 unordered_map 的键值
E-commerce RPA robot helps brand e-commerce to achieve high traffic
S32Kxxx bootloader之UDS bootloader
.env.xxx 文件,加了常量,卻undefined
安全协议重点
电商RPA机器人,助力品牌电商抢立流量高点
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
Write some suggestions to current and future doctoral students to sort out and share
How to display real-time 2D map after rviz is opened
随机推荐
ADO. Net SqlConnection object usage summary
Linux foundation - centos7 offline installation of MySQL
vs2015 AdminDeployment.xml
2021 RoboCom 世界机器人开发者大赛-高职组复赛
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决
Matplotlib common settings
Practical application and extension of plain framework
Postgresql源码(57)HOT更新为什么性能差距那么大?
Current situation and future development trend of Internet of things
常见的积分商城游戏类型有哪些?
【ES实战】ES上的安全性运行方式
Yunxin small class | common cognitive misunderstandings in IM and audio and video
How to realize parallel replication in MySQL replication
Door level modeling - after class exercises
使用uni-simple-router,动态传参 TypeError: Cannot convert undefined or null to object
问题随记 —— /usr/bin/perl is needed by MySQL-server-5.1.73-1.glibc23.x86_64
ConcurrentSkipListMap——跳表原理
. env. XXX file, with constant, but undefined
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
电商RPA机器人,助力品牌电商抢立流量高点