QT day05
1 SQLite数据库的操作
2 学生成绩管理系统
1 SQLite数据库的操作
1.1 问题
安装SQLite数据库,在SQLite命令行实现创建数据库,并建立学生成绩,练习增、删、改、查等操作。
1.2 方案
SQLite 是一个开源的,轻型的嵌入式关系数据库,是遵守ACID的关系型数据库管理系统,它包含,在一个相对小的C库中。实现自包容、零配置、支持事务的SQL数据库引擎。 其特点是高度便携、使用方便、结构紧凑、高效、可靠。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如 Tcl、C#、PHP、Java等,还有ODBC接口。与其他数据库管理系统不同,SQLite 的安装和运行非常简单,在大多数情况下,只要确保SQLite的二进制文件存在即可开始创建、连接和使用数据库。本案例首先需要大家安装好SQLite3,然后通过Sqlite命令创建数据库,对数据库进行增删查改的操作,熟悉SQLite的基本命令。
1.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:安装SQLite3。
在线安装命令
$sudo apt-get install SQLite3
也可以复制deb包进行离线安装,如果使用的是老师给的ubuntu64虚拟机镜像,那么里面已经有安装了SQLite3。
$sudo dpkg-i libsqlite3-0_3.7.9-2ubuntu1.2_amd64.deb sqlite3_3.7.9-2ubuntu1.2_amd64.deb
步骤二: SQLite创建数据库
安装完成后,在终端提示符下输入sqlite3 studentDB.db(studentDB.db是学员成绩数据库名)回车,如图-1所示:
$sqlite3 studentDB.db
执行完后,命令提示符自动跳转到"SQLITE>"状态, 此时可以输入“ .databases” 命令来检查它是否在数据库列表中,如图-2所示:
步骤三:创建学生成绩数据表。
在终端输入创建表命令:
$sqlite>create table Student (
>id INTEGER primary key,
>name VARCHAR(20) not null,
>score REAL not null);
创建的表名为Student,表字段分别为用户的id,id作为表的键值,具有唯一性,name字段用来保存学生的姓名,是 20个字符的字符串,score 字段为实型,记录学员的成绩。
分别使用“.tables” “.schema”命令可以查看表的创建是否成功,列出表的完整信息,如下所示:
步骤四:插入数据项到表中。
SQLite 的“INSERT INTO”语句用于向数据库的某个表中添加新的数据,在终端输入命令:
sqlite>insert into Student values(006,‘闻西’,98.8) ;
sqlite>insert into Student values(007,‘阿七’,87) ;
sqlite>insert into Student values(008,‘阿发’,88.8) ;
分别在数据表中插入了三条数据,如图-5所示:
在终端输入命令:
sqlite>select * from Student ;
查看表中的所有数据项,如图-6所示,可以看到刚刚插入数据表中的两天数据。
步骤五:修改数据。
SQLite 的 UPDATE 查询用于修改表中已有的记录,可以使用带有 WHERE 子句的 UPDATE 查询来更新选定的数据,否则所有的行都会被更新,修改阿七同学的成绩为59.9分,在终端输入命令:
sqlite>update Student set score=59.9 where name=‘阿七’;
步骤六:删除数据项,删除表。
SQLite 的 DELETE 查询用于删除表中已有的记录,可以使用带有 WHERE 子句的 DELETE 查询来删除选定行,否则所有的记录都会被删除,在终端输入命令:
sqlite> delete from Student where score<90;
sqlite>select * from Student;
删除所有成绩小于90分的学员,那么小于90的记录项将被删除。
SQLite 的“DROP TABLE ”语句用来删除表定义及其所有相关数据“DROP TABLE ”使用要特别小心,因为一旦一个表被删除,表中所有信息也将永远丢失,命令如下:
sqlite>DROP TABLE Student;
2 学生成绩管理系统
2.1 问题
通过QT实现学生成绩管理系统。
2.2 方案
Qt为数据库访问提供的QtSql模块实现了数据库和Qt应用程序的无缝集成,同时为开发人员提供了一套与平台无关和具体所用数据库均无关的调用接口。这使得开发人员只需掌握基本的SQL语句,就能进行简单的数据库应用程序开发。本案例通过Qt图形界面实现对Sqlite数据库的操作。
首先通过QSqlDatabase创建数据库,并且建立连接。在新创建数据库中创建表,表中包括id,name,score字段。设计Ui,使用QTableView控件显示数据项,通过插入,删除,修改按钮对数据库进行操作,通过排序按钮,对数据进行排序显示。
2.3 步骤
实现此案例需要按照如下步骤进行。
步骤一:创建新工程。
终端输入:qtcreator或点击桌面qt图标。启动Qt创造器。
$qtcreator
选择菜单"file/file or project",在"新建"对话框中依次选择"application"和"QT widgets Application",并点击"choose…"
在"项目介绍和位置"中指定项目的名称为:Sqlite_demo,并选择存储路径,Qt会在该路径下创建工程目录,点击"next"
在"kits"中选择"Desktop Qt 5.4.1 Gcc 64bit",前面打勾,点击"next"
在"Class information"中选择"QDialog"作为"Base class",并将"class name"设置为"sqlDialog",勾选"Generate form",点击"next" ,点击"finsh"。
步骤二:使用设计师设计界面
双击sqlDialog.ui,打开Qt设计师,开始设计界面,如图-10所示:
步骤三:编写源程序头文件ErnieDialog.h。
双击sqlDialog.h文件,编写头文件,代码如下:
#ifndef SQLDIALOG_H
#define SQLDIALOG_H
#include
#include
#include
#include
#include
#include
namespace Ui {
class SqlDialog;
}
class SqlDialog : public QDialog
{
Q_OBJECT
public:
explicit SqlDialog(QWidget *parent = 0);
~SqlDialog();
bool createDB(void);
bool createTable(void);
public slots:
void insertItem(void);
void deleteItem(void);
void modifyItem(void);
void queryTable(void);
void sortTable(void);
private:
Ui::SqlDialog *ui;
QSqlDatabase db;
};
#endif // SQLDIALOG_H
上述代码中,以下代码:
bool createDB(void);
bool createTable(void);
private:
Ui::SqlDialog *ui;
QSqlDatabase db;
QSqlDatabase db实例化一个对象,用于对数据库的操作,声明创建数据库和创建表的函数。
上述代码中,以下代码:
public slots:
void insertItem(void);
void deleteItem(void);
void modifyItem(void);
void queryTable(void);
void sortTable(void);
自定义槽函数,分别用于插入数据,删除数据,修改数据,查询排序。
步骤四:编写源程序头文件sqlDialog.cpp。
双击sqlDialog.cpp文件,编写头文件,代码如下:
#include “sqlDialog.h”
#include “ui_sqlDialog.h”
#include
SqlDialog::SqlDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SqlDialog)
{
ui->setupUi(this);
createDB();
createTable();
//连接插入按钮和槽函数
connect(ui->insertButton,SIGNAL(clicked()),this,SLOT(insertItem()));
//连接删除按钮和槽函数
connect(ui->deleteButton,SIGNAL(clicked()),this,SLOT(deleteItem()));
//连接修改按钮和槽函数
connect(ui->modifyButton,SIGNAL(clicked()),this,SLOT(modifyItem()));
//连接排序按钮和槽函数
connect(ui->sortButton,SIGNAL(clicked()),this,SLOT(sortTable()));
queryTable();
}
SqlDialog::~SqlDialog()
{
delete ui;
}
//创建数据库
bool SqlDialog::createDB(){
//建立与数据库的连接,参数指定使用哪一个数据库驱动
//支持QMYSQL、QPSQL…
//判断默认的链接是否存在
if(QSqlDatabase::contains(db.connectionName())){
db = QSqlDatabase::database(db.connectionName());
}
else{
db = QSqlDatabase::addDatabase(“QSQLITE”);
}
//qDebug(db.connectionName().toStdString().c_str());
//设置数据库的名字
db.setDatabaseName(“menu.db”);
//建立和数据库的连接之前必须打开数据库
if(db.open() == false){
//严重的错误
QMessageBox::critical(0,“Data Error”,db.lastError().text());
return false;
}
return true;
}
//创建表
bool SqlDialog::createTable(){
//QSqlQuery类提供了SQL语句执行和操作手
QSqlQuery query;
QString str = QString(“create table Student (
id INTEGER primary key ,
name VARCHAR(20) not null,
score REAL not null)”);
//如果已经存在了那么不会执性创建表,相当于不执行本条语句,不用去判断是否存在
//如果存在了返回bool false;成功了返回bool ok;
if( query.exec(str) ){//创建表
//qDebug(“Success!”);
return true;
}
else{
//qDebug(“Failure”);
return false;
}
}
//插入
void SqlDialog::insertItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
QString name(ui->nameEdit->text().toStdString().c_str());
double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString insertSql = QString(QObject::tr(“insert into Student values(%1,’%2’,%3)”)).arg(num).arg(name).arg(score);
qDebug() << insertSql.toStdString().c_str();
//执行sql语句
query.exec(insertSql);
//查询并显示
queryTable();
//eg:
//query.exec(QString(QObject::tr(“insert into Student values(%1,’%2’,%3)”)).arg(num).arg(name).arg(score));
//query.exec(QObject::tr(“insert into Student values(20160702,‘张飞’,78.5)”));
}
//删除
void SqlDialog::deleteItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
// QString name(ui->nameEdit->text().toStdString().c_str());
//double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString deleteSql = QString(QObject::tr(“delete from Student where id=%1”)).arg(num);
qDebug() << deleteSql.toStdString().c_str();
//执行sql语句
query.exec(deleteSql);
//查询并显示
queryTable();
}
//修改
void SqlDialog::modifyItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
//QString name(ui->nameEdit->text().toStdString().c_str());
double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString modifySql = QString(
QObject::tr(“update Student set score=%1 where id=%2”)).arg(score).arg(num);
qDebug() << modifySql.toStdString().c_str();
//执行sql语句
query.exec(modifySql);
query.exec(“commit”);
//查询并显示
queryTable();
}
//查询
void SqlDialog::queryTable(void){
QString str = QString (“select * from Student order by id”);
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(str);
ui->menuTableView->setModel(model);
}
//排序
void SqlDialog::sortTable(void){
QString value = ui->valueComboBox->currentText();
QString condition(“asc”);
if(ui->condCombo->currentIndex()){
condition = “desc”;
}
else{
condition = “asc”;
}
QString str = QString (“select * from Student order by %1 %2”).arg(value).arg(condition);
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(str);
ui->menuTableView->setModel(model);
}
在构造函数中,首先通过createDB();连接数据库,如果数据库不存在则创建数据库,新建的数据库指定为QSQLITE数据库,数据库名为menu.db,然后连接数据库。createTable();函数通过sql语句“create table Student (id INTEGER primary key , name VARCHAR(20) not null, score REAL not null)”,创建了Student表。
步骤五:编译运行
代码编辑完后,即可对工程进行编译,点击绿色按钮,即可编译运行,如果代码有错,会给出错误信息,运行结果如下图-11所示:
2.4 完整代码
本案例的头文件完整代码如下所示:
#ifndef SQLDIALOG_H
#define SQLDIALOG_H
#include
#include
#include
#include
#include
#include
namespace Ui {
class SqlDialog;
}
class SqlDialog : public QDialog
{
Q_OBJECT
public:
explicit SqlDialog(QWidget *parent = 0);
~SqlDialog();
bool createDB(void);
bool createTable(void);
public slots:
void insertItem(void);
void deleteItem(void);
void modifyItem(void);
void queryTable(void);
void sortTable(void);
private:
Ui::SqlDialog *ui;
QSqlDatabase db;
};
#endif // SQLDIALOG_H
本案例的sqlDialog.cpp完整代码如下所示:
#include “sqlDialog.h”
#include “ui_sqldialog.h”
#include
SqlDialog::SqlDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SqlDialog)
{
ui->setupUi(this);
createDB();
createTable();
//连接插入按钮和槽函数
connect(ui->insertButton,SIGNAL(clicked()),this,SLOT(insertItem()));
//连接删除按钮和槽函数
connect(ui->deleteButton,SIGNAL(clicked()),this,SLOT(deleteItem()));
//连接修改按钮和槽函数
connect(ui->modifyButton,SIGNAL(clicked()),this,SLOT(modifyItem()));
//连接排序按钮和槽函数
connect(ui->sortButton,SIGNAL(clicked()),this,SLOT(sortTable()));
queryTable();
}
SqlDialog::~SqlDialog()
{
delete ui;
}
//创建数据库
bool SqlDialog::createDB(){
//建立与数据库的连接,参数指定使用哪一个数据库驱动
//支持QMYSQL、QPSQL…
//判断默认的链接是否存在
if(QSqlDatabase::contains(db.connectionName())){
db = QSqlDatabase::database(db.connectionName());
}
else{
db = QSqlDatabase::addDatabase(“QSQLITE”);
}
//qDebug(db.connectionName().toStdString().c_str());
//设置数据库的名字
db.setDatabaseName(“menu.db”);
//建立和数据库的连接之前必须打开数据库
if(db.open() == false){
//严重的错误
QMessageBox::critical(0,“Data Error”,db.lastError().text());
return false;
}
return true;
}
//创建表
bool SqlDialog::createTable(){
//QSqlQuery类提供了SQL语句执行和操作手
QSqlQuery query;
QString str = QString(“create table Student (
id INTEGER primary key ,
name VARCHAR(20) not null,
score REAL not null)”);
//如果已经存在了那么不会执性创建表,相当于不执行本条语句,不用去判断是否存在
//如果存在了返回bool false;成功了返回bool ok;
if( query.exec(str) ){//创建表
//qDebug(“Success!”);
return true;
}
else{
//qDebug(“Failure”);
return false;
}
}
//插入
void SqlDialog::insertItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
QString name(ui->nameEdit->text().toStdString().c_str());
double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString insertSql = QString(QObject::tr(“insert into Student values(%1,’%2’,%3)”)).arg(num).arg(name).arg(score);
qDebug() << insertSql.toStdString().c_str();
//执行sql语句
query.exec(insertSql);
//查询并显示
queryTable();
//eg:
//query.exec(QString(QObject::tr(“insert into Student values(%1,’%2’,%3)”)).arg(num).arg(name).arg(score));
//query.exec(QObject::tr(“insert into Student values(20160702,‘张飞’,78.5)”));
}
//删除
void SqlDialog::deleteItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
// QString name(ui->nameEdit->text().toStdString().c_str());
//double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString deleteSql = QString(QObject::tr(“delete from Student where id=%1”)).arg(num);
qDebug() << deleteSql.toStdString().c_str();
//执行sql语句
query.exec(deleteSql);
//查询并显示
queryTable();
}
//修改
void SqlDialog::modifyItem(void){
QSqlQuery query;
int num = ui->numEdit->text().toInt();
//QString name(ui->nameEdit->text().toStdString().c_str());
double score = ui->scoreEdit->text().toDouble();
//构造sql语句
QString modifySql = QString(
QObject::tr(“update Student set score=%1 where id=%2”)).arg(score).arg(num);
qDebug() << modifySql.toStdString().c_str();
//执行sql语句
query.exec(modifySql);
query.exec(“commit”);
//查询并显示
queryTable();
}
//查询
void SqlDialog::queryTable(void){
QString str = QString (“select * from Student order by id”);
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(str);
ui->menuTableView->setModel(model);
}
//排序
void SqlDialog::sortTable(void){
QString value = ui->valueComboBox->currentText();
QString condition(“asc”);
if(ui->condCombo->currentIndex()){
condition = “desc”;
}
else{
condition = “asc”;
}
QString str = QString (“select * from Student order by %1 %2”).arg(value).arg(condition);
QSqlQueryModel *model = new QSqlQueryModel;
model->setQuery(str);
ui->menuTableView->setModel(model);
}
本案例的main.cpp完整代码如下所示:
#include “sqlDialog.h”
#include
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
SqlDialog w;
if(w.createDB()==false){
return -1;
}
w.show();
return a.exec();
}