各位用户为了找寻关于QT连接MYSQL数据库的详细步骤的资料费劲了很多周折。这里教程网为您整理了关于QT连接MYSQL数据库的详细步骤的相关资料,仅供查阅,以下为您介绍关于QT连接MYSQL数据库的详细步骤的详细内容
第一步要加入对应的数据库模块(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:Qt5.9mingw53_32bin(根据自己的目录) 我的QT版本是5.9。数据库是否打开用户是否错误是否有这个数据库。
2.创建表
? 1 2QSqlQuery q;
q.
exec
(
"create table student(id int primary key auto_increment, name varchar(255), age int, score int)ENGINE=INNODB;"
);
3.给表插入数据
方法1(单行插入)
? 1q.
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 13q.
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 2QSqlQuery q;
q.
exec
(
"update student set score=76 where name='李四'"
);
4.删除表
? 1 2QSqlQuery q;
q.
exec
(
"delete from student where name='张三'"
);
5.遍历表
? 1 2 3 4 5 6 7 8 9 10 11QSqlQuery 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