使用前提
必须要安装对应数据库驱动。
头文件
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QtSql>
#include <QtSql/QSqlTableModel>
#include <QtSql/QSqlQueryModel>
#include <QSqlRelationalTableModel>
#include <QSqlQuery>
#include <QFile>
#include <QFileDialog>
上传
单个文件上传MySQL:
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("ip");
db.setDatabaseName("dbNmae");
db.setUserName("dbUser");
db.setPassword("dbPwd");
if (!db.open())
QMessageBox::warning(this,"提示",QString("%1").arg(db.lastError().text()));
else
{
QDateTime *datatime=new QDateTime(QDateTime::currentDateTime());
QString Udatetime = datatime->toString("yyyy-MM-dd hh:mm:ss");
QString UFileName = QFileDialog::getOpenFileName();
QString filename = UFileName.split("/").at(UFileName.split("/").size()-1);
//转换为字节数组
QByteArray mapData;
QFile file(UFileName);
file.open(QIODevice::ReadOnly);
mapData = file.readAll();
file.close();
QSqlQuery query;
query.prepare("INSERT INTO ufile ( project, stage, TP , BigOne, FileName, FileDate, UName, UTime) values"
"( :FileName, :FileDate,)");
query.bindValue(":FileName", filename);
query.bindValue(":FileDate", mapData);
if (!query.exec()) {
qDebug() << query.lastError();
return
}
qDebug()<<"上传成功";
}
下载
下载MySQL中的文件
QSqlQuery readquery(db);
QByteArray databa;
if (readquery.exec("select FileDate from ufile where FileName = '文件名'")) {
QSqlRecord myrecord = readquery.record();
if (readquery.next()) {
databa = readquery.value(myrecord.indexOf("FileDate")).toByteArray(); //读取二进制对象
}
}
QFile mybfile("filename"); //写到本地文件,存什么后缀文件名就写什么
mybfile.open(QIODevice::WriteOnly);
mybfile.write(databa);
mybfile.close();
qDebug() << "write data successfully!";
|