一、postgresql 数据库的安装和配置
主要用到的命令:
安装 PostgreSQL:
sudo apt-get update
sudo apt-get install postgresql postgresql-client
安装完毕后,系统会创建一个数据库超级用户 postgres。
sudo -i -u postgres 进入数据库
sudo -u postgres psql
psql (10.22 (Ubuntu 10.22-0ubuntu0.18.04.1)) Type "help" for help.
\q 退出 PostgreSQL
PostgreSQL 安装完成后默认是已经启动的,但是也可以通过下面的方式来手动启动服务。
sudo /etc/init.d/postgresql start
# 开启
sudo /etc/init.d/postgresql stop
# 关闭
sudo /etc/init.d/postgresql restart # 重启
本实验中重新创建了数据库,并设置服务器的 ip 地址为 127.0.0.1,服务器使用的端口为 5432,
设置用户名为 postgres,数据库的名称为 ttt:
createdb -h 127.0.0.1 -p 5432 -U postgres -w ttt
进入数据库 ttt:
\c ttt
You are now connected to database "ttt" as user "postgres".
设置登录密码并两次确认:
\password
Enter new password for user "postgres":
Enter it again:
\l 查看目前数据库列表得到:
二、数据库获取图片
QSqlDatabase 类处理与数据库的连接,要使用这个类,头文件需要导入 QSqlDatabase 库:
#include <QSqlDatabase>,并在 qmake.pro 文件中加入 SQL 数据库支持:QT += sql。按照
设计 Qt 界面,将实现过程分为四个部分。
1. 设置第一个按钮“
open”触发的函数:on_pushButton_clicked(),在函数体中首先通过
QSqlDatabase *db 增加一个数据库,在操作之前首先用 QPSQL 去驱动链接它,然后设置数据
库的相关参数包括主机名、服务器端口、数据库用户名、数据库密码、数据库名,然后调用 open() 去激活对数据库的连接。
2. 设置第二个按钮“save”触发的函数:on_pushButton_2_clicked(),在函数体中,首先打开 摄像头保存的图片文件到全局变量 QImage 中,设置保存图片的字符数组为 imageData,然后将 字符数组和数据库缓冲区 buffer 绑定以便数据的写入。然后将图片写入缓冲区,再将将图片直接 转换为 base64 数据。接着,传入 QSqlDatabase 实例对数据库进行操作。 对与 QSqlQuery 类,Qt 中对数据库的操作主要通过 QSqlQuery 实现,QSqlQuery 提供了执行数据库语句的方法,在 Qt 中利用 QSqlQuery 类实现了执行 SQL 语句。它可以返回所有的 执行结果,当建立好数据库连接好后可以通过使用 QSqlQuery::exec(),如下面的语句: QSqlQuery query query.exec("SELECT num, data FROM imge"),当创建一个 QSqlQuery 对象后,可以被指定的 QSqlDatabase 对象连接来使用。常见的数据库操作包括添 加,查询,删除,和修改等操作。
本实验中需要向数据库中写入图片,首先对数据库进行预处理向其中添加新的值,行添加的
值首先用“?”代替,后面再用 imageData 添加进去以此来完成数据绑定。
QSqlQuery query;
query.prepare("INSERT INTO imge VALUES (1, ?)");
query.addBindValue(imageData);
QSqlQuery 类中当执行 exec()后会把指针放在记录集中第一个记录之上,所以需要调用
QSqlQuery::next()来获取第一个数据,通过 while 循环体来遍历所有表中的数据。
while (query.next()) {
QByteArray data = query.value(1).toByteArray();
int num = query.value(0).toInt();
qDebug() << num << ": " << data;}
QSqlQuery::value()函数得到当前记录区域中的数据,QSqlQuery::value()默认返回的是
一个 QVariant 类型,Qt 提供了几种可选的类型支持,都是 C++的基本的类型,如:int,QString, QByteArray。本实验中得到的返回值为 1 的时候返回关于图片的 ByteArray()类型并将值赋给 data,而当返回值为 0 的时候返回 Int()类型。至此已经完成了将图片与数据库中的特定数组进行 绑定,并将特定格式的图片储存在数据库中。
3. 设置第三个按钮“
get”触发的函数:on_pushButton_3_clicked(),在函数体中,首先从已
经刷新得到的 imge 中查询获取图片信息,然后将 Base64 格式的图片解码为 Local8bit 的图片
用于显示,图片的显示通过将 label 和图片进行绑定,并设置图片适应 label 的大小显示。至此完
成了数据库中保存图片的显示。
4. 界面展示:
mainwindow.cpp
//将图片存到服务器中
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QSqlQuery>
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
#include <QBuffer>
#include<QVariant>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QSqlDatabase *db=new QSqlDatabase(QSqlDatabase::addDatabase("QPSQL"));
db->setHostName("127.0.0.1"); //设置数据库的主机ip
db->setPort(5432); // 服务使用的端口
db->setUserName("postgres"); //数据库用户名
db->setPassword("123456"); //数据库密码
db->setDatabaseName("ttt"); //数据库名
qDebug()<<db->open(); //成功返回 true,失败返回false,调用open()去激活对数据库的连接。
}
void MainWindow::on_pushButton_2_clicked()
{
QImage image("/home/kkk/桌面/tt.jpg");
QByteArray imageData; //保存图片数据的字符数组
QBuffer buffer(&imageData); //将字符数组与buffer缓存区绑定,以便写入数据
image.save(&buffer, "jpg"); //将图片以jpg格式写入buffer
imageData = imageData.toBase64();
QSqlQuery query; //传入QSqlDatabase实例
query.prepare("INSERT INTO imge VALUES (1, ?)");
query.addBindValue(imageData);
query.exec(); //执行
if (!query.execBatch()) {
QMessageBox::critical(0, QObject::tr("Database Error"),
query.lastError().text()); //刷新检查最新出现的错误
}
query.exec("SELECT num, data FROM imge"); //从imge中中读取num和data
while (query.next()) {
QByteArray data = query.value(1).toByteArray(); //得到的返回值为1的时候返回关于图片的ByteArray()类型并将值赋给data
int num = query.value(0).toInt();
qDebug() << num << ": " << data; //将num和data对应的信息输出到控制台上
}
query.exec();
}
void MainWindow::on_pushButton_3_clicked()
{
QSqlQuery query;
query.exec("SELECT * FROM imge");
while (query.next()) {
QString data = query.value(1).toString();
int num = query.value(0).toInt();
qDebug() << num << ": " << data;
QPixmap image;
image.loadFromData(QByteArray::fromBase64(data.toLocal8Bit()));
ui->label->setPixmap(image);
//调整合理尺寸
ui->label->resize( ui->label->size());
}
}
mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QSqlQuery>
#include <QMainWindow>
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_clicked();
void on_pushButton_2_clicked();
void on_pushButton_3_clicked();
private:
Ui::MainWindow *ui;
QImage Qimg;
};
#endif // MAINWINDOW_H
main.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QSqlQuery>
#include <QCoreApplication>
#include <QSqlDatabase>
#include <QDebug>
#include <QMessageBox>
#include <QSqlError>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.ui
.pro
QT += core gui
QT += sql
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
CONFIG += c++11
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
SOURCES += \
main.cpp \
mainwindow.cpp
HEADERS += \
mainwindow.h
FORMS += \
mainwindow.ui
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
需要每次对数据库的表格进行数据清空操作:delete from imge;