第一步要加入对应的数据库模块(sql)在工程文件(.pro)介绍几个类(也是对应的头文件)
QSqlError提供SQL数据库错误信息的类 QSqlQuery提供了执行和操作SQL语句的方法 QSqlQueryDatabase 处理到数据库的连接1.数据库的连接
 //添加mysql数据库 
        QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL"); 
        //连接数据库
        db.setHostName("127.0.0.1");//数据库服务器IP
        db.setUserName("root");  //数据库用户名
        db.setPassword("root");//数据库用户名密码
        db.setDatabaseName("sys"); //数据库名
        if(db.open()==false)
        {
            QMessageBox::information(this,"数据库打开失败",db.lastError().text());
            return;
        }
如果失败可能是QT连接mysql数据库要一个库(自己下载 libmysql.dll)把库文件放在QT的安装目录D:\Qt\5.9\mingw53_32\bin(根据自己的目录) 我的QT版本是5.9。数据库是否打开用户是否错误是否有这个数据库。
2.创建表
QSqlQuery q;
q.exec("create table student(id int primary key auto_increment, name varchar(255), age int, score int)ENGINE=INNODB;");
3.给表插入数据
方法1(单行插入)
q.exec("insert into student(id, name, age,score) values(1, '张三', 24,80);");
方法2 (多行插入)又分为 odbc 风格 与 oracle风格
1. odbc 风格
 q.prepare("insert into student(name, age,score) values(?, ?, ?)");  //?是占位符
   QVariantList name;
   name<<"素数"<<"等待"<<"安安";
   QVariantList age;
   age<<-2<<12<<14;
   QVariantList score;
   score<<0<<89<<90;
   //给字段绑定相应的值 按顺序绑定
   q.addBindValue(name);
   q.addBindValue(age);
   q.addBindValue(score);
   //执行预处理命令
   q.execBatch();
要加#include<QVariantList>头文件 字段要按顺序绑定
2.orace风格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;
  //给字段绑定 顺序任意因为根据:+自定义名字
  q.bindValue(":n",name);
  q.bindValue(":s",score);
  q.bindValue(":a",age);
  //执行预处理命令
  q.execBatch();
根据占位符区别所以字段顺序可以任意
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
    {
        //以下标
        //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();
    }
