第一步要加入对应的数据库模块(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();
}
到此这篇关于qt连接mysql数据库的文章就介绍到这了,更多相关qt连接mysql数据库内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!