欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

QT連接MYSQL數(shù)據(jù)庫的詳細(xì)步驟

 更新時(shí)間:2021年07月07日 14:40:59   作者:牛牛ly  
這篇文章主要介紹了QT連接MYSQL數(shù)據(jù)庫的詳細(xì)步驟,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

 第一步要加入對應(yīng)的數(shù)據(jù)庫模塊(sql)在工程文件(.pro)介紹幾個(gè)類(也是對應(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 student");
    while(q.next())   //遍歷完為false
    {
        //以下標(biāo)
        //qDebug()<<q.value(0).toInt()<<q.value(1).toString()<<q.value(2).toInt() 
        <<q.value(3).toInt();
        //以字段
        qDebug()<<q.value("id").toInt()<<q.value("name").toString()<<q.value("age").toInt() 
        <<q.value("score").toInt();
    }

到此這篇關(guān)于QT連接MYSQL數(shù)據(jù)庫的文章就介紹到這了,更多相關(guān)QT連接MYSQL數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論