在工程中添加定义:QT+=sql
头文件定义:
include <QSqlDatabase>
class MyDatabase
{
public:
MyDatabase();
void connectMYSQL();
void createDB();
void initDB();
QSqlDatabase database;
}
MyDatabase函数实现:
void MyDatabase::connectMYSQL()
{
if (QSqlDatabase::contains("myConnect"))//判断testConnect连接是否存在并连接
{
database = QSqlDatabase::database("myConnect");
}
else //未连接则新建数据库连接
{
database=QSqlDatabase::addDatabase("QMYSQL","myConnect");//创建数据库连接,并为其命名testConnect
database.setHostName("127.0.0.1"); //连接数据库主机名,这里需要注意(若填的为”127.0.0.1“,出现不能连接,则改为localhost)
database.setPort(3306); //连接数据库端口号,与设置一致
database.setUserName("root"); //数据库用户名,与设置一致
database.setPassword("123456"); //数据库密码,与设置一致
}
if(!database.open())
{
qDebug()<<"fail to connect mysql:"<<database.lastError().text();
return;
}
}
创建数据库、数据表
//创建数据库、数据表
void MyDatabase::createDB()
{
QString querystring;
//创建数据库
database = QSqlDatabase::database("myConnect");
querystring = "CREATE DATABASE IF NOT EXISTS student_info";
database.exec(querystring);
if (database.lastError().isValid())
{
qDebug()<<"Create database failed."<<database.lastError();
return;
}
//创建数据表student
database.setDatabaseName("student_info");
if(!database.open())
{
qDebug()<<"database open failed";
return;
}
querystring =
"CREATE TABLE IF NOT EXISTS student_info.Student\
(\
Name varchar(20),\
NO varchar(20) primary key,\
Sex varchar(20),\
Tell varchar(20),\
Address varchar(30), \
Hobbies varchar(30)\
)";
database.exec(querystring);//执行创建数据表语句
if (database.lastError().isValid())
{
qDebug()<<"Student table creat failed:" << database.lastError();
return;
}
//支持中文
database.exec("alter table Student convert to character set utf8");
}
初始化数据库(添加原始值)
//初始化数据库(添加原始值)
void MyDatabase::insertDB()
{
QSqlQuery query(database);
query.exec("insert into Student values('张1', '2018010235', '男','12116588966','开心小区12#103','球,游泳')");
query.exec("insert into Student values('李4', '2018020156', '男','15665487200','开心小区9#602','足球')");
query.exec("insert into Student values('灵儿', '2018020202', '女','10202020202','玄武区爱情公寓2#202','Dota')");
if(!query.exec())
{
qDebug() << "Error: Fail to insert ." << query.lastError();
}
}
查询数据
void MyDatabase::QueryData()
{
QSqlQuery query(database);
query.exec("select * from Student");
while(query.next())
{
qDebug()<<query.value(0).toString()<<query.value(1).toString()<<query.value(2).toString()
<<query.value(3).toString()<<query.value(4).toString()<<query.value(5).toString();
}
}