继下午成功连接数据库之后,再接再厉做了Qt读写Mysql的操作(以下过程都是建立在能连接数据库的前提下)。代码不讲究,能实现功能。
1.照旧新建项目 ReadandWrite
2.修改.pro文件:添加 QT += sql
3.进入界面文件,添加两个按钮,右击按钮,选择“转为槽”
自动进入mainwindow.cpp文件。分别添加了querydatabes()和insertdatabes()方法。这两个方法的实现我是放在一个叫conn.h的头文件里,所以要#include"conn.h"
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "conn.h"
#include "main.cpp"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
querydatabes();
}
void MainWindow::on_pushButton_2_clicked()
{
insertdatabes();
}
4.新建头文件,包含读写操作,对我这个菜鸟来说暂时不谈代码好坏,能实现功能就好。。
#ifndef CONN_H
#define CONN_H
#include <QSqlDatabase>
#include <QDebug>
#include <QtSql>
bool querydatabes()
{
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("fruit");
db.setUserName("root");
db.setPassword("");
if(db.open())
{
qDebug() << "database is established!";
}
else
{
qDebug() << "build error!";
return false;
}
QSqlQuery query;
bool success = query.exec("select * from user");
if(!success){
qDebug() << "查询user失败";
}
QSqlRecord rec = query.record();
qDebug() << "user表的字段总数为:" << rec.count();
query.seek(-1);
while(query.next()){
qDebug() << query.value(1).toString() << query.value(2).toString()<< query.value(3).toString()<< query.value(4).toString() << query.value(5).toString();
}
db.close();
}
bool insertdatabes()
{
QSqlDatabase db1 = QSqlDatabase::addDatabase("QMYSQL");
db1.setHostName("localhost");
db1.setDatabaseName("fruit");
db1.setUserName("root");
db1.setPassword("");
if(db1.open())
{
qDebug() << "database is established!";
}
else
{
qDebug() << "build error!";
return false;
}
QSqlQuery query1;
query1.prepare("insert into user values(?,?,?,?,?,?) ");
// query1.bindValue(0,1);主键不能赋值
query1.bindValue(1,"1");
query1.bindValue(2,"12");
query1.bindValue(3,"sd");
query1.bindValue(4,"ad");
query1.bindValue(5,"ad");
bool success = query1.exec();
if(!success){
QSqlError lastError = query1.lastError();
qDebug() << lastError.driverText() << lastError.databaseText();
//return;
}
db1.close();
}
#endif // CONN_H
效果:
点击查询,应用程序输出查询结果。点击插入,会在数据库中插入代码里面预先写好的值。