QT學習筆記(16) QT5的數據庫操作
阿新 • • 發佈:2017-09-04
libmysql gets pan detail ima () 數據庫服務 oca else
一、編譯驅動
參考博客:http://blog.csdn.net/xian0gang/article/details/49791351
因為從QT5以來,它就自帶數據庫驅動了,所以我們不需要費事的編譯也可以使用數據庫。QT訪問MySQL需要兩個動態鏈接庫文件,一個是QT自己的mysql驅動插件,另一個是MySQL提供的動態鏈接庫,缺一不可。
在程序裏指定要訪問的數據庫是MySQL,QT會自動的加載MySQL驅動插件,其實實現依賴於MySQL的動態鏈接庫訪問MySQL。
(1)訪問MySQL提供的動態鏈接庫
在這就不提怎麽安裝MySQL 了,在目錄 lib 裏可以找到 MySQL 的動態鏈接庫 libmysql.dll 和 libmysqld.lib
找到這兩個文件,然後把它們復制到我們QT安裝的目錄下,如下:
(2)測試數據庫連接
在項目文件.pro中,加入sql模塊,然後在用到所需的類是必須包含頭文件。
QT_HelloWorld18.pro
1 #數據庫操作,需要加載sql模塊 2 QT += core gui sql 3 4 greaterThan(QT_MAJOR_VERSION, 4): QT += widgets 5 6 TARGET = QT_HelloWorld18 7 TEMPLATE = app 8 9 10 SOURCES += main.cpp11widget.cpp 12 13 HEADERS += widget.h 14 15 FORMS += widget.ui
widget.cpp
1 #include "widget.h" 2 #include "ui_widget.h" 3 #include <QDebug> 4 #include <QtSql/QSqlDatabase> 5 #include <QtSql/QSqlError> 6 #include <QMessageBox> 7 #include <QString> 89 Widget::Widget(QWidget *parent) : 10 QWidget(parent), 11 ui(new Ui::Widget) 12 { 13 ui->setupUi(this); 14 15 //打印QT支持的數據庫驅動 16 qDebug() << QSqlDatabase::drivers(); 17 18 //添加MySql數據庫 19 QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); 20 //連接數據庫 21 db.setHostName(QString::fromLocal8Bit("127.0.0.1"));//數據庫服務器IP 22 db.setUserName(QString::fromLocal8Bit("root"));//數據庫用戶名 23 db.setPassword(QString::fromLocal8Bit("ccs"));//密碼 24 db.setDatabaseName(QString::fromLocal8Bit("db_qt_test"));//使用哪個數據庫 25 26 if(db.open() == true) 27 { 28 QMessageBox::information(this,QString::fromLocal8Bit("正確"), 29 QString::fromLocal8Bit("連接數據庫成功")); 30 return ; 31 } 32 else 33 { 34 QMessageBox::warning(this,QString::fromLocal8Bit("錯誤"), 35 db.lastError().text()); 36 return ; 37 } 38 } 39 40 Widget::~Widget() 41 { 42 delete ui; 43 }
QT學習筆記(16) QT5的數據庫操作