当前位置:网站首页>【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;
}

第四步:运行程序

边栏推荐
- 2021 robocom world robot developer competition - semi finals of higher vocational group
- The essence of software architecture
- 哈工大《信息内容安全》课程知识要点和难点
- Matplotlib common charts
- 电商RPA机器人,助力品牌电商抢立流量高点
- Postgresql随手记(10)动态执行EXECUTING语法解析过程
- 力扣今日题-241. 为运算表达式设计优先级
- What are the common types of points mall games?
- Windows 7 安装MYSQL 错误:1067
- Notblank and notempty
猜你喜欢

Use vb Net to convert PNG pictures into icon type icon files

Why does blocprovider feel similar to provider?

kubernetes资源对象介绍及常用命令(三)

Algolia's search needs are almost closed

Concurrentskiplistmap -- principle of table skipping

【ES实战】ES上的安全性运行方式

Using uni simple router, dynamically pass parameters typeerror: cannot convert undefined or null to object

Zero foundation tutorial of Internet of things development

Redis master-slave synchronization

MT manager test skiing Adventure
随机推荐
Daily three questions 6.29
Redis data types and application scenarios
Anomaly-Transformer (ICLR 2022 Spotlight)复现过程及问题
ADO.NET 之sqlConnection 对象使用摘要
[es practice] safe operation mode on ES
安全协议重点
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决
from pip._internal.cli.main import main ModuleNotFoundError: No module named ‘pip‘
[leetcode] length of the last word [58]
Linux foundation - centos7 offline installation of MySQL
Daily three questions 6.30
PostgreSQL source code (57) why is the performance gap so large in hot update?
ARP message header format and request flow
哈工大《信息内容安全》课程知识要点和难点
Redis AOF日志
Kubernetes resource object introduction and common commands (III)
Matplotlib common charts
[swoole Series 1] what will you learn in the world of swoole?
物联网应用技术专业是属于什么类
在代码中使用SqlCommand对象