QT連接MYSQL數(shù)據(jù)庫的詳細(xì)步驟
第一步要加入對(duì)應(yīng)的數(shù)據(jù)庫模塊(sql)在工程文件(.pro)介紹幾個(gè)類(也是對(duì)應(yīng)的頭文件)
- QSqlError提供SQL數(shù)據(jù)庫錯(cuò)誤信息的類
- QSqlQuery提供了執(zhí)行和操作SQL語句的方法
- QSqlQueryDatabase處理到數(shù)據(jù)庫的連接
1.數(shù)據(jù)庫的連接
//添加mysql數(shù)據(jù)庫 QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL"); //連接數(shù)據(jù)庫 db.setHostName("127.0.0.1");//數(shù)據(jù)庫服務(wù)器IP db.setUserName("root"); //數(shù)據(jù)庫用戶名 db.setPassword("root");//數(shù)據(jù)庫用戶名密碼 db.setDatabaseName("sys"); //數(shù)據(jù)庫名 if(db.open()==false) { QMessageBox::information(this,"數(shù)據(jù)庫打開失敗",db.lastError().text()); return; }
如果失敗可能是QT連接mysql數(shù)據(jù)庫要一個(gè)庫(自己下載 libmysql.dll)把庫文件放在QT的安裝目錄D:\Qt\5.9\mingw53_32\bin(根據(jù)自己的目錄)我的QT版本是5.9。數(shù)據(jù)庫是否打開用戶是否錯(cuò)誤是否有這個(gè)數(shù)據(jù)庫。
2.創(chuàng)建表
QSqlQuery q; q.exec("create table student(id int primary key auto_increment, name varchar(255), age int, score int)ENGINE=INNODB;");
3.給表插入數(shù)據(jù)
方法1(單行插入)
q.exec("insert into student(id, name, age,score) values(1, '張三', 24,80);");
方法2 (多行插入)又分為 odbc 風(fēng)格與oracle風(fēng)格
1. odbc 風(fēng)格
q.prepare("insert into student(name, age,score) values(?, ?, ?)"); //?是占位符 QVariantList name; name<<"素?cái)?shù)"<<"等待"<<"安安"; QVariantList age; age<<-2<<12<<14; QVariantList score; score<<0<<89<<90; //給字段綁定相應(yīng)的值 按順序綁定 q.addBindValue(name); q.addBindValue(age); q.addBindValue(score); //執(zhí)行預(yù)處理命令 q.execBatch();
要加#include<QVariantList>頭文件 字段要按順序綁定
2.orace風(fēng)格d
//占位符 :+自定義名字 q.prepare("insert into student(name, age,score) values(:n, :a,:s)"); QVariantList name; name<<"夸克"<<"紅米"<<"鴻蒙"; QVariantList age; age<<5<<10<<3; QVariantList score; score<<77<<89<<99; //給字段綁定 順序任意因?yàn)楦鶕?jù):+自定義名字 q.bindValue(":n",name); q.bindValue(":s",score); q.bindValue(":a",age); //執(zhí)行預(yù)處理命令 q.execBatch();
根據(jù)占位符區(qū)別所以字段順序可以任意
3.更新表
QSqlQuery q; q.exec("update student set score=76 where name='李四'");
4.刪除表
QSqlQuery q; q.exec("delete from student where name='張三'");
5.遍歷表
QSqlQuery q; q.exec("select *from stude
到此這篇關(guān)于QT連接MYSQL數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)QT連接MYSQL數(shù)據(jù)庫內(nèi)容請(qǐng)搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。