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

第四步:运行程序

边栏推荐
- VIM color the catalogue
- Is it safe to buy funds on Great Wall Securities?
- Redis master-slave synchronization
- ADO.NET之sqlCommand对象
- 比较通俗易懂的PID理解
- Concepts of dictionary, hash table and array
- Y53. Chapter III kubernetes from introduction to mastery -- ingress (26)
- Is there a piece of code that makes you convinced by human wisdom
- [leetcode] length of the last word [58]
- Daily three questions 6.29
猜你喜欢

安全协议重点

Use pair to do unordered_ Key value of map

Chapter 6 data flow modeling

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

Yunxin small class | common cognitive misunderstandings in IM and audio and video

写给当前及未来博士研究生一些建议整理分享

notBlank 和 notEmpty

Future trend and development of neural network Internet of things

Is there a piece of code that makes you convinced by human wisdom
![Various global files related to [.Net core] program](/img/89/32623abf30d3dc92a3cdb1710a624f.png)
Various global files related to [.Net core] program
随机推荐
Using SqlCommand objects in code
2022-07-01: at the annual meeting of a company, everyone is going to play a game of giving bonuses. There are a total of N employees. Each employee has construction points and trouble points. They nee
物联网技术应用属于什么专业分类
cookie、session、tooken
cookie、session、tooken
Future trend and development of neural network Internet of things
.env.xxx 文件,加了常量,卻undefined
Commemorate becoming the first dayus200 tripartite demo contributor
边缘计算概述
Redis RDB snapshot
Redis AOF log
vs2015 AdminDeployment. xml
notBlank 和 notEmpty
What are the common types of points mall games?
What is the difference between memory leak and memory overflow?
excel如何打开100万行以上的csv文件
Linux foundation - centos7 offline installation of MySQL
Redis AOF日志
ADO. Net SqlConnection object usage summary
Practical application and extension of plain framework