首先在qt中使用数据库,需要我们根据qt源码自行编译库,具体编译细节请参考Qt 中编译数据库驱动 | 爱编程的大丙 (subingwen.cn)(如有侵权,请联系我删除)。
前提:在mysql添加一个db1数据库,在db1内添加一个fam表:
create database db1;
use db1;
create table fam(
-> id int primary key,
-> name varchar(20),
-> address varchar(40),
-> age int,
-> gender varchar(20));
mysql> show tables;
+---------------+
| Tables_in_db2 |
+---------------+
| fam |
+---------------+
1 row in set (0.00 sec)
mysql> desc fam;
+---------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+-------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
| address | varchar(40) | YES | | NULL | |
| age | int | YES | | NULL | |
| gender | varchar(20) | YES | | NULL | |
+---------+-------------+------+-----+---------+-------+
5 rows in set (0.00 sec)
mysql> insert into fam (id,name,address,age,gender) values(0,'tom','shanghai',20,'male');
Query OK, 1 row affected (0.00 sec)
mysql> insert into fam (id,name,address,age,gender) values(1,'liutao','shanghai',23,'male');
Query OK, 1 row affected (0.00 sec)
mysql> insert into fam (id,name,address,age,gender) values(2,'bin','suzhou',25,'male');
Query OK, 1 row affected (0.00 sec)
mysql> insert into fam (id,name,address,age,gender) values(3,'hong','suzhou',34,'female');
Query OK, 1 row affected (0.00 sec)
mysql> select * from fam;
+----+--------+----------+------+--------+
| id | name | address | age | gender |
+----+--------+----------+------+--------+
| 0 | tom | shanghai | 20 | male |
| 1 | liutao | shanghai | 23 | male |
| 2 | bin | suzhou | 25 | male |
| 3 | hong | suzhou | 34 | female |
+----+--------+----------+------+--------+
4 rows in set (0.00 sec)
mysql>
好了,现在我们数据库里有这样一个表:
下面我们通过qt写一个小demo实现对数据库的一些简单操作:
1.首先在pro文件中添加 sql ;
QT += core gui sql
ui界面设计如下:
具体功能:通过connect连接数据库,show显示数据库内具体的数据,add将各个lineedit内的信息添加到数据库内的表内,update进行表内数据更新。
头文件如下:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_5_clicked();
void on_pushButton_6_clicked();
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void on_pushButton_3_clicked();
private:
Ui::MainWindow *ui;
QSqlDatabase db;
};
#endif // MAINWINDOW_H
前提我们已经编译好需要的动态(静态)库:
2.实例化一个QSqlDatabase类对象,需要调用
QSqlDatabase::addDatabase("驱动名");
我们先调用QSqlDatabase::drivers()来查看支持的数据库驱动:
QStringList type=QSqlDatabase::drivers();
qDebug()<
我们可以看到支持的数据库驱动:
("QSQLITE", "QMARIADB", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7"),由于安装的是mysql数据库,我们选择 "QMYSQL"。
实例化一个QSqlDatabase对象db1;
db=QSqlDatabase::addDatabase("QMYSQL");
接下来我们设置下连接属性:
db.setHostName("localhost");
db.setDatabaseName("db2");
db.setUserName("root");
db.setPassword("password");
db.setPort(3306);
由于我的数据库安装在本机,对应的localhost即本机ip地址;
3.connect按钮的槽函数即实现连接数据库功能:
void MainWindow::on_pushButton_5_clicked()
{
if(db.open())
{
ui->textEdit->append("connect success!");
QMessageBox::information(this,"connection info","connect success!");
}
else
{
QString errInfo=db.lastError().text();
QMessageBox::information(this,"connection info","connect failed!"+errInfo);
}
}
result:
4.show按钮实现显示数据库内表的数据:
void MainWindow::on_pushButton_6_clicked()
{
QString sql="select * from fam";
QSqlQuery query;
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}
}
result:
5.通过add按钮向表内添加数据:
//添加
void MainWindow::on_pushButton_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
QString name=ui->lineEdit_2->text();
QString addres=ui->lineEdit_3->text();
int age=ui->lineEdit_4->text().toInt();
QString gender=ui->lineEdit_5->text();
QString sql=QString("insert into fam (id,name,address,age,gender) values ('%1','%2','%3','%4','%5')").arg(index).arg(name).arg(addres).arg(age).arg(gender);
if(query.exec(sql)&&addres!=""&&gender!="")
{
db.commit();
ui->lineEdit->clear();
ui->lineEdit_2->clear();
ui->lineEdit_3->clear();
ui->lineEdit_4->clear();
ui->lineEdit_5->clear();
ui->textEdit->insertPlainText(QString::number(index)+' ');
ui->textEdit->insertPlainText(name+' ');
ui->textEdit->insertPlainText(addres+' ');
ui->textEdit->insertPlainText(QString::number(age)+' ');
ui->textEdit->insertPlainText(gender+="\n");
}
else
{
db.rollback();
QMessageBox::information(this,"connection info","add failed!");
}
}
result:
6.通过delete按钮实现删除记录功能:(这里通过主键id进行删除)
void MainWindow::on_pushButton_2_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
if(ui->lineEdit->text()!="")
{
QString sql=QString("delete from fam where id='%1' ").arg(index);
if(query.exec(sql))
{
db.commit();
}
else
{
QMessageBox::information(this,"connection info","delete failed!");
db.rollback();
}
}
ui->textEdit->clear();
QString sql="select * from fam";
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}
}
7.通过update进行数据更新:
void MainWindow::on_pushButton_3_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
QString name=ui->lineEdit_2->text();
QString addres=ui->lineEdit_3->text();
int age=ui->lineEdit_4->text().toInt();
QString gender=ui->lineEdit_5->text();
QString sql=QString("insert into fam (id,name,address,age,gender) values ('%1','%2','%3','%4','%5')").arg(index).arg(name).arg(addres).arg(age).arg(gender);
if(query.exec(sql)&&addres!=""&&gender!="")
{
db.commit();
ui->lineEdit->clear();
ui->lineEdit_2->clear();
ui->lineEdit_3->clear();
ui->lineEdit_4->clear();
ui->lineEdit_5->clear();
ui->textEdit->insertPlainText(QString::number(index)+' ');
ui->textEdit->insertPlainText(name+' ');
ui->textEdit->insertPlainText(addres+' ');
ui->textEdit->insertPlainText(QString::number(age)+' ');
ui->textEdit->insertPlainText(gender+="\n");
}
else
{
db.rollback();
QMessageBox::information(this,"connection info","add failed!");
}
}
整个实现:
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include
#include
#include
#include
#include
#include
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_5_clicked();
void on_pushButton_6_clicked();
void on_pushButton_clicked();
void on_pushButton_2_clicked();
void on_pushButton_4_clicked();
void on_pushButton_3_clicked();
private:
Ui::MainWindow *ui;
QSqlDatabase db;
};
#endif // MAINWINDOW_H
main.cpp:
#include "mainwindow.h"
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.cpp:
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
db=QSqlDatabase::addDatabase("QMYSQL");
QStringList type=QSqlDatabase::drivers();
qDebug()<textEdit->append("connect success!");
QMessageBox::information(this,"connection info","connect success!");
}
else
{
QString errInfo=db.lastError().text();
QMessageBox::information(this,"connection info","connect failed!"+errInfo);
}
}
void MainWindow::on_pushButton_6_clicked()
{
QString sql="select * from fam";
QSqlQuery query;
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}
}
//添加
void MainWindow::on_pushButton_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
QString name=ui->lineEdit_2->text();
QString addres=ui->lineEdit_3->text();
int age=ui->lineEdit_4->text().toInt();
QString gender=ui->lineEdit_5->text();
QString sql=QString("insert into fam (id,name,address,age,gender) values ('%1','%2','%3','%4','%5')").arg(index).arg(name).arg(addres).arg(age).arg(gender);
if(query.exec(sql)&&addres!=""&&gender!="")
{
db.commit();
ui->lineEdit->clear();
ui->lineEdit_2->clear();
ui->lineEdit_3->clear();
ui->lineEdit_4->clear();
ui->lineEdit_5->clear();
ui->textEdit->insertPlainText(QString::number(index)+' ');
ui->textEdit->insertPlainText(name+' ');
ui->textEdit->insertPlainText(addres+' ');
ui->textEdit->insertPlainText(QString::number(age)+' ');
ui->textEdit->insertPlainText(gender+="\n");
}
else
{
db.rollback();
QMessageBox::information(this,"connection info","add failed!");
}
}
//删除
void MainWindow::on_pushButton_2_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
if(ui->lineEdit->text()!="")
{
QString sql=QString("delete from fam where id='%1' ").arg(index);
if(query.exec(sql))
{
db.commit();
}
else
{
QMessageBox::information(this,"connection info","delete failed!");
db.rollback();
}
}
ui->textEdit->clear();
QString sql="select * from fam";
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}
}
//查询
void MainWindow::on_pushButton_4_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
if(ui->lineEdit->text()!="")
{
QString sql=QString("select * from fam where id='%1' ").arg(index);
query.exec(sql);
ui->textEdit->clear();
while(query.next())
{
ui->textEdit->insertPlainText(QString::number(query.value(0).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(1).toString())+' ');
ui->textEdit->insertPlainText(QString(query.value(2).toString())+' ');
ui->textEdit->insertPlainText(QString::number(query.value(3).toInt())+' ');
ui->textEdit->insertPlainText(QString(query.value(4).toString()+="\n"));
}
}
}
//更新
void MainWindow::on_pushButton_3_clicked()
{
db.transaction();
QSqlQuery query;
int index=ui->lineEdit->text().toInt();
QString name=ui->lineEdit_2->text();
QString addres=ui->lineEdit_3->text();
int age=ui->lineEdit_4->text().toInt();
QString gender=ui->lineEdit_5->text();
QString sql=QString("insert into fam (id,name,address,age,gender) values ('%1','%2','%3','%4','%5')").arg(index).arg(name).arg(addres).arg(age).arg(gender);
if(query.exec(sql)&&addres!=""&&gender!="")
{
db.commit();
ui->lineEdit->clear();
ui->lineEdit_2->clear();
ui->lineEdit_3->clear();
ui->lineEdit_4->clear();
ui->lineEdit_5->clear();
ui->textEdit->insertPlainText(QString::number(index)+' ');
ui->textEdit->insertPlainText(name+' ');
ui->textEdit->insertPlainText(addres+' ');
ui->textEdit->insertPlainText(QString::number(age)+' ');
ui->textEdit->insertPlainText(gender+="\n");
}
else
{
db.rollback();
QMessageBox::information(this,"connection info","add failed!");
}
}