第一步要加入对应的数据库模块(sql)在工程文件(.pro)介绍几个类(也是对应的头文件)
- QSqlError提供SQL数据库错误信息的类
- QSqlQuery提供了执行和操作SQL语句的方法
- QSqlQueryDatabase处理到数据库的连接
1.数据库的连接
?
1 2 3 4 5 6 7 8 9 10 11 12 | //添加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.创建表
?
1 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(单行插入)
?
1 | q.exec("insert into student(id, name, age,score) values(1, '张三', 24,80);"); |
方法2 (多行插入)又分为 odbc 风格与oracle风格
1. odbc 风格
?
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | //占位符 :+自定义名字 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.更新表
?
1 2 | QSqlQuery q; q.exec("update student set score=76 where name='李四'"); |
4.删除表
?
1 2 | QSqlQuery q; q.exec("delete from student where name='张三'"); |
5.遍历表
?
1 2 3 4 5 6 7 8 9 10 11 | 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数据库内容请搜索钦钦技术栈以前的文章或继续浏览下面的相关文章希望大家以后多多支持钦钦技术栈!
原文链接:https://blog.csdn.net/qq_41328470/article/details/117917793
版权声明:本文(即:原文链接:https://www.qin1qin.com/catagory/6441/)内容由互联网用户自发投稿贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 630367839@qq.com 举报,一经查实,本站将立刻删除。