Qt旧版本(以5.7.1.0为例)连接mysql数据库 代码部分

该部分内容(按钮,折叠)师承W3schools的这一篇文章。我在如何使用hexo搭建个人博客的文章中推荐过该网站。

事实上,你现在所看到的这个网页是使用html标记语言写的,因为hexo的主题会覆盖一些我们自定义的html样式,所以我们需要让拥有自定义样式的html文件跳过渲染。你可以在这一篇文章中学习它。我的魔法屋也将计划以这样的形式建设。

在QT中打印当前QT版本支持的数据库代码

	QT += core sql
	QT -= gui

	CONFIG += c++11

	TARGET = untitled
	CONFIG += console
	CONFIG -= app_bundle

	TEMPLATE = app

	SOURCES += main.cpp

	# The following define makes your compiler emit warnings if you use
	# any feature of Qt which as 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 you use 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  
	#include <QCoreApplication>
	#include <QtSql/QSqlDatabase>
	#include <QDebug>

	int main(int argc, char *argv[])
	{
		QCoreApplication a(argc, argv);
		qDebug() << QSqlDatabase::drivers();
		return a.exec();
	}	

检查是否可以成功连接数据库代码

untitled.pro 代码无需更改,或可以删去QT += sql

	#include <QCoreApplication>
	#include <QtSql/QSqlDatabase>
	#include <QDebug>

	int main(int argc, char *argv[])
	{
		QCoreApplication a(argc, argv);
		QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
		//链接数据库
		db.setHostName("127.0.0.1");
		db.setUserName("root");
		db.setPassword("123456");
		db.setDatabaseName("mysql");
		if(!db.open()){
			qDebug() << "0";
		}else{
			qDebug() << "1";
		}
		exit(0);
		return a.exec();
	}

这里将上一步在QT中打印当前QT版本支持的数据库代码删掉了。不删除,直接添加新的代码也是可以的,两部分不影响。