QT连接mysql数据库方式

时间:2020-07-11
本文章向大家介绍QT连接mysql数据库方式,主要包括QT连接mysql数据库方式使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

QT连接mysql 对版本和系统的影响不大

环境变量

Mysql 有很多版本,在线下载版本,离线版本,免安装版本

在线下载的版本可以自己选择需要的功能和插件,

离线版本,直接一键安装就行

免安装版本  需要环境变量,和通过命令集 启动mysql数据库的使用,

都有优点

我都是在先安装最新版本的

2020/7/11号

安装方面就不写了,QT方面选择全面安装

Mysql方面选择全面 安装

然后把Mysql文件种的

这些版本按照  对应版本和32或64,的文件都添加到QT对应的文件中

可以百度 有特别多,我看过大概200个左右内容都差不多

至于 没有库文件,和需要自己编译的情况,还有报错的情况,可以忽略,有效果就行

然后QT创建一个项目

 命令窗口和win窗口都可以的

这块选择这两个版本

代码

QT       += core gui
QT       +=sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
#include "mainwindow.h"

#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QSqlQuery>
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;


    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");

    db.setHostName("127.0.0.1"); //数据库服务器IP
        db.setUserName("root");//用户名
        db.setPassword("493893279");//密码
        db.setDatabaseName("Mydata");//使用的数据库
        qDebug()<<"DatabaseConnect";
       if(!db.open()){
        qDebug()<<"数据读取失败";

       }else
       {
        db.exec("SET NAMES'gbk'");
        

       }





    w.show();
    return a.exec();
}

内容就是这样

点击运行没有报错就行

 效果如下

关于在如何使用mysql读写数据和创建数据删除数据   

暂时不会

原文地址:https://www.cnblogs.com/suiyi78/p/13284570.html