前言
SQLite(sql)是一款开源轻量级的数据库软件,不须要server,能够集成在其余软件中,很是适合嵌入式系统。
Qt5以上版本能够直接使用SQLite(Qt自带驱动)。
sql
用法
1 准备
- 引入SQL模块
在Qt项目文件(.pro文件)中,加入SQL模块:
QT += sql
- 引用头文件
在须要使用SQL的类定义中,引用相关头文件。例如:
#include <QSqlDatabase> #include <QSqlError> #include <QSqlQuery>
2 使用
1. 创建数据库
检查链接、添加数据库驱动、设置数据库名称、数据库登陆用户名、密码。数据库
QSqlDatabase database; if (QSqlDatabase::contains("qt_sql_default_connection")) { database = QSqlDatabase::database("qt_sql_default_connection"); } else { database = QSqlDatabase::addDatabase("QSQLITE"); database.setDatabaseName("MyDataBase.db"); database.setUserName("XingYeZhiXia"); database.setPassword("123456"); }
上述代码解释:
(1)第一行中,创建了一个QSqlDatabase
对象,后续的操做要使用这个对象。
(2)if
语句用来检查指定的链接(connection)是否存在。这里指定的链接名称(connection name)是qt_sql_default_connection
,这是Qt默认链接名称。实际使用时,这个名称能够任意取。若是判断此链接已经存在,那么QSqlDatabase::contains()
函数返回true。此时,进入第一个分支,QSqlDatabase::database()
返回这个链接。
(3)若是这个链接不存在,则进入else
分支,须要建立链接,并添加数据库。在else
分支第一行,addDatabase()
的参数QSQLITE
是SQLite对应的驱动名,不能改。并且须要注意的是,addDatabase()
的第二个参数被省略了,第二个参数的默认参数就是上面提到的Qt默认链接名称qt_sql_default_connection
。若是须要使用自定义的链接名称(若是程序须要处理多个数据库文件的话就会这样),则应该加入第二个参数,例如
express
database = QSqlDatabase::addDatabase("QSQLITE", "my_sql_connection);
这个时候,若是在另外一个地方须要判断my_sql_connection
链接是否存在,就应该使用if (QSqlDatabase::contains("my_sql_connection"))
。
(4)else
分支第二行中,setDatabaseName()
的参数是数据库文件名。若是这个数据库不存在,则会在后续操做时自动建立;若是已经存在,则后续的操做会在已有的数据库上进行。
(5)else
分支后面两行,设置用户名和密码。用户名,密码均可以随便取,也能够省略。
数组
2. 打开数据库
使用open()
打开数据库,并判断是否成功。注意,在第一步检查链接是否存在时,若是链接存在,则在返回这个链接的时候,会默认将数据库打开。app
if (!database.open()) { qDebug() << "Error: Failed to connect database." << database.lastError(); } else { // do something }
若是打开成功,则进入else分支。对数据库的操做都须要在else分支中进行。函数
3. 关闭数据库
数据库操做完成后,最好关闭。布局
database.close();
4. 操做数据库
对数据库进行操做须要用到QSqlQuery类,操做前必须定义一个对象。下面举例说明操做方法。操做须要使用SQLite语句,本文中的几个例子会使用几个经常使用的语句,关于SQLite语句的具体信息请参考SQLite相关资料。
例1:建立表格
建立一个名为student的表格,表格包含三列,第一列是id,第二列是名字,第三列是年龄。
this
QSqlQuery sql_query; QString create_sql = "create table student (id int primary key, name varchar(30), age int)"; sql_query.prepare(create_sql); if(!sql_query.exec()) { qDebug() << "Error: Fail to create table." << sql_query.lastError(); } else { qDebug() << "Table created!"; }
代码解释:
(1)第一行定义一个QSqlQuery
对象。
(2)第二行是一个QString
,其中的内容是SQLite语句。对数据库的操做,都是用SQLite的语句完成的,把这些指令以QString类型,经过prepare
函数,保存在QSqlQuery对象中。也可将指令,以QString形式直接写在exec()
函数的参数中,例如:
spa
sql_query.exec("create table student (id int primary key, name varchar(30), age int)");
建立表格语句:create table <table_name> (f1 type1, f2 type2,…);
create table
是建立表格的语句,也可用大写CREATE TABLE
;student是表格的名称,能够任意取;括号中是表格的格式,上述指令代表,表格中有三列,第一列的名称(表头)是id,这一列储存的数据类型是int,第二列名称是name,数据类型是字符数组,最多有30个字符(和char(30)的区别在于,varchar的实际长度是变化的,而char的长度始终是给定的值),第三列的名称是age,数据类型是int。
若是sql_query.exec()
执行成功,则建立表格成功。
3d
例2:插入数据
在刚才建立的表格中,插入一行数据。
QString insert_sql = "insert into student values (?, ?, ?)"; sql_query.prepare(insert_sql); sql_query.addBindValue(max_id+1); sql_query.addBindValue("Wang"); sql_query.addBindValue(25); if(!sql_query.exec()) { qDebug() << sql_query.lastError(); } else { qDebug() << "inserted Wang!"; } if(!sql_query.exec("INSERT INTO student VALUES(3, \"Li\", 23)")) { qDebug() << sql_query.lastError(); } else { qDebug() << "inserted Li!"; }
插入语句:insert into <table_name> values (value1, value2,…);
insert into
是插入语句,student是表格名称,values()是要插入的数据。这里,咱们插入了2组数据。插入第一组数据的时候,用addBindValue
来替代语句中的?
,替代的顺序与addBindValue
调用的顺序相同。插入第二组数据的时候,则是直接写出完整语句。
例3:更新数据(修改数据)
QString update_sql = "update student set name = :name where id = :id"; sql_query.prepare(update_sql); sql_query.bindValue(":name", "Qt"); sql_query.bindValue(":id", 1); if(!sql_query.exec()) { qDebug() << sql_query.lastError(); } else { qDebug() << "updated!"; }
语句:update <table_name> set <f1=value1>, <f2=value2>… where <expression>;
更新(修改)的语句是update...set...
,其中student是表格名称,name是表头名称(即第二列),:name是待定的变量,where用于肯定是哪一组数据,:id也是待定变量。bindValue(" ", " ")
函数用来把语句中的待定变量换成肯定值。
例4:查询数据
(1)查询部分数据
QString select_sql = "select id, name from student"; if(!sql_query.exec(select_sql)) { qDebug()<<sql_query.lastError(); } else { while(sql_query.next()) { int id = sql_query.value(0).toInt(); QString name = sql_query.value(1).toString(); qDebug()<<QString("id:%1 name:%2").arg(id).arg(name); } }
语句select <f1>, <f2>, ... from <table_name>;
select是查询指令;<f1>
等等是要查询的变量(即表头),中间用逗号隔开;from ...指定表格。
上述语句是说查询student表中的 id 和 name 。执行查询以后,用sql_query.value(int)
来得到数据。一样地,value(0)
表示第一个数据,即 id,value(1)
表示name。注意:value()
函数的返回值类型是QVariant
,所以要用toInt()
等函数转换成特定的类型。
(2)查询所有数据
QString select_all_sql = "select * from student"; sql_query.prepare(select_all_sql); if(!sql_query.exec()) { qDebug()<<sql_query.lastError(); } else { while(sql_query.next()) { int id = sql_query.value(0).toInt(); QString name = sql_query.value(1).toString(); int age = sql_query.value(2).toInt(); qDebug()<<QString("id:%1 name:%2 age:%3").arg(id).arg(name).arg(age); } }
语句select * from <table_name>;
查询全部数据用 * 表示。用while(sql_query.next())
用来遍历全部行。一样用value()
得到数据。
(3)查询最大id
QString select_max_sql = "select max(id) from student"; int max_id = 0; sql_query.prepare(select_max_sql); if(!sql_query.exec()) { qDebug() << sql_query.lastError(); } else { while(sql_query.next()) { max_id = sql_query.value(0).toInt(); qDebug() << QString("max id:%1").arg(max_id); } }
这个就是在语句中用max
来获取最大值。
例5:删除与清空
(1)删除一条数据
QString delete_sql = "delete from student where id = ?"; sql_query.prepare(delete_sql); sql_query.addBindValue(0); if(!sql_query.exec()) { qDebug()<<sql_query.lastError(); } else { qDebug()<<"deleted!"; }
语句delete from <table_name> where <f1> = <value>
delete用于删除条目,用where给出限定条件。例如此处是删除 id = 0的条目。
(2)清空表格(删除全部)
QString clear_sql = "delete from student"; sql_query.prepare(clear_sql); if(!sql_query.exec()) { qDebug() << sql_query.lastError(); } else { qDebug() << "table cleared"; }
这里没有用where给出限制,就会删除全部内容。
QT读写Sqlite数据库的三种方式
QT对一些基本的数据库的访问封装,可谓是极大的方便的咱们开发人员,如今咱们就来讲下QT对Sqlite这个数据库的读写,Sqlite是一个比较小型的本地数据库,对于保存一些软件配置参数或量不是很大的数据是至关的方便,Qt自己已经自带了Sqlite的驱动,直接使用相关的类库便可,这篇咱们主要来讲明QT访问Sqlite数据库的三种方式(即便用三种类库去访问),分别为QSqlQuery、QSqlQueryModel、QSqlTableModel,对于这三种类库,可看为一个比一个上层,也就是封装的更厉害,甚至第三种QSqlTableModel,根本就不须要开发者懂SQL语言,也能操做Sqlite数据库。
一、首先使用QSqlQuery来访问
咱们先要在工程中包含与数据库相关的几个头文件#include <QtSql/QSqlDatabase> 、#include <QtSql/QSqlRecord>、#include <QtSql/QSqlQuery>
访问的数据库内容结构为:
-
#include <QtWidgets/QApplication>
-
#include <QCoreApplication>
-
#include <QDebug>
-
#include <QtSql/QSqlDatabase>
-
#include <QtSql/QSqlQuery>
-
#include <QtSql/QSqlRecord>
-
typedef struct _testInfo //假定数据库存储内容
-
{
-
QString UsreName;
-
QString IP;
-
QString Port;
-
QString PassWord;
-
QString Type;
-
}testInfo;
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
QVector<testInfo> infoVect; //testInfo向量,用于存储数据库查询到的数据
-
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
-
db.setDatabaseName(QApplication::applicationDirPath() + "/CONFIG/" + "CONFIG.db");
-
if (!db.open())
-
{
-
return 0;
-
}
-
/**************************使用QSqlQuery操做数据库**************************/
-
QSqlQuery query; //执行操做类对象
-
//查询数据
-
query.prepare("SELECT * FROM T_USER_MANAGE");
-
query.exec(); //执行
-
QSqlRecord recode = query.record(); //recode保存查询到一些内容信息,如表头、列数等等
-
int column = recode.count(); //获取读取结果的列数
-
QString s1 = recode.fieldName(0); //获取第0列的列名
-
while (query.next())
-
{
-
testInfo tmp;
-
tmp.UsreName = query.value("UsreName").toString();
-
tmp.IP = query.value("IP").toString();
-
tmp.Port = query.value("Port").toString();
-
tmp.PassWord = query.value("PassWord").toString();
-
tmp.Type = query.value("Type").toString();
-
infoVect.push_back(tmp); //将查询到的内容存到testInfo向量中
-
}
-
for (int i=0; i<infoVect.size(); i++) //打印输出
-
{
-
qDebug() << infoVect[i].UsreName << ":" \
-
<< infoVect[i].IP << ":" \
-
<< infoVect[i].Port << ":" \
-
<< infoVect[i].PassWord << ":" \
-
<< infoVect[i].Type;
-
}
-
//插入数据
-
query.prepare("INSERT INTO T_USER_MANAGE (UsreName, IP, Port, PassWord, Type) VALUES (:UsreName, :IP, :Port, :PassWord, :Type)");
-
query.bindValue(":UserName", "user4"); //给每一个插入值标识符设定具体值
-
query.bindValue(":IP", "192.168.1.5");
-
query.bindValue(":Port", "5004");
-
query.bindValue(":PassWord", "55555");
-
query.bindValue(":Type", "operator");
-
query.exec();
-
//更改表中 UserName=user4 的Type属性为admin
-
query.prepare("UPDATE T_USER_MANAGE SET Type='admin' WHERE UserName='user4'");
-
query.exec();
-
//删除表中 UserName=user4的用户信息
-
query.prepare("DELETE FROM T_USER_MANAGE WHERE UserName='user4'");
-
query.exec();
-
#endif
-
/**************************使用QSqlQuery操做数据库END***********************/
编译输出:
二、使用QSqlQueryModel来访问
QSqlQueryModel类带有Model字样,相信你已经猜到咱们能够用他来关联试图,就能把数据库的内容显示到视图上,固然,常规的操做也是能够的,可是咱们只说说怎么用这个类来把数据库中的内容显示到是视图中,这里咱们选择的视图类为QTableView,直接上代码吧
-
#include <QtWidgets/QApplication>
-
#include <QCoreApplication>
-
#include <QDebug>
-
#include <QString>
-
#include <QTableView>
-
#include <QtSql/QSqlDatabase>
-
#include <QtSql/QSqlQueryModel>
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
-
db.setDatabaseName(QApplication::applicationDirPath() + "/CONFIG/" + "CONFIG.db");
-
if (!db.open())
-
{
-
return 0;
-
}
-
QSqlQueryModel *model = new QSqlQueryModel;
-
model->setQuery("SELECT * FROM T_USER_MANAGE", db); //从给定的数据库db执行sql操做, db需预先制定并打开
-
int column = model->columnCount(); //获取列数
-
int row = model->rowCount(); //获取行数
-
model->setHeaderData(0, Qt::Horizontal, QStringLiteral("用户名")); //设置表头,如不设置则使用数据库中的默认表头
-
model->setHeaderData(1, Qt::Horizontal, QStringLiteral("IP地址"));
-
model->setHeaderData(2, Qt::Horizontal, QStringLiteral("端口"));
-
model->setHeaderData(3, Qt::Horizontal, QStringLiteral("密码"));
-
model->setHeaderData(4, Qt::Horizontal, QStringLiteral("用户类型"));
-
QTableView *view = new QTableView; //定义视图,只能用于显示,不能修改数据库
-
view->setFixedSize(500, 200);
-
view->setModel(model);
-
view->show();
-
return a.exec();
-
}
编译运行一下:
三、最后使用QSqlTableModel来访问
最后咱们来讲说使用QSqlTableModel这个类去操做Sqlite数据库,这个类比上两个封装的更完全,即便咱们不懂SQL语言,也能实现对Sqlite数据库的操做,而且这个类也能够经过视图来显示修改数据库内容,这里我就拿这个类作了个用户管理模块,其实也能够通用与其余任何一个模块,只要在生成对象时传入sqlite的数据库名及要操做的表名便可。
在这个例子中,我实现了一个KSDemoDlg类,实际上是一个对话框类,里边包含了sqlite数据库的显示、修改等等功能,首先来看下效果(常规的增删改查功能都有):
当咱们点击增长、修改时,右边的编辑框便为可编辑状态(说明下,右边的编辑框是随着加载的数据库表变化而变化的,简而言之就是能够不作修改就能操做别的Sqlite数据库),完毕肯定后便写进数据库,同时也在左边的表格中显示
头文件:
-
#ifndef __KSDEMODLG_H__
-
#define __KSDEMODLG_H__
-
#include <QDialog>
-
#include <QPushButton>
-
#include <QLineEdit>
-
#include <QLabel>
-
#include <QComboBox>
-
#include <QGroupBox>
-
#include <QTableView>
-
#include <QtSql/QSqlTableModel>
-
#include <QtSql/QSqlDatabase>
-
class KSDemoDlg : public QDialog
-
{
-
Q_OBJECT
-
enum {UPDATE, INSERT};
-
int m_operator;
-
public:
-
explicit KSDemoDlg(QString databaseName, QString dataTableName, QWidget *parent = 0 );
-
~KSDemoDlg();
-
private:
-
void UiInit();
-
protected slots:
-
void onNewButtonClicked();
-
void onQueryButtonClicked();
-
void onUpdateButtonClicked();
-
void onDeleteButtonClicked();
-
void onPrimaryKeyLineEditEmpty(const QString & text);
-
void onCurrentTableViewClicked(const QModelIndex & index);
-
void onOKButtonClicked();
-
void onCancelButtonClicked();
-
private:
-
QSqlDatabase m_db;
-
QString m_DBName;
-
QString m_DBTableName;
-
private:
-
QTableView* m_TabView;
-
QSqlTableModel* m_model;
-
private:
-
QList<QLineEdit*> m_infoEditList;
-
QList<QLabel*> m_infoLabelList;
-
QPushButton m_OKButton;
-
QPushButton m_CancelButton;
-
private:
-
/*全部用户信息容器组*/
-
QGroupBox m_Group;
-
QLabel m_PrimaryKeyLabel;
-
QLineEdit m_PrimaryKeyLineEdit;
-
QPushButton m_QueryButton;
-
QPushButton m_NewButton;
-
QPushButton m_UpdateButton;
-
QPushButton m_DeleteButton;
-
/*所选择用户信息容器组*/
-
QGroupBox m_SelectGroup;
-
};
-
#endif // __KSDEMODLG_H__
.cpp文件
-
#include <QtWidgets/QApplication>
-
#include <QCoreApplication>
-
#include <QString>
-
#include <QFormLayout>
-
#include <QVBoxLayout>
-
#include <QHBoxLayout>
-
#include <QMessageBox>
-
#include <QtSql/QSqlRecord>
-
#include <QDebug>
-
#include "KSDemoDlg.h"
-
/**************************************************************************
-
* 函数名称:KSDemoDlg
-
* 函数功能:用户管理对话框构造函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
KSDemoDlg::KSDemoDlg(QString databaseName, QString dataTableName, QWidget *parent):QDialog(parent, Qt::WindowCloseButtonHint | Qt::WindowMinMaxButtonsHint | Qt::WindowStaysOnTopHint),
-
m_Group(this), m_PrimaryKeyLabel(this), m_PrimaryKeyLineEdit(this), m_QueryButton(this), m_NewButton(this), m_UpdateButton(this), m_DeleteButton(this), m_TabView(NULL),m_model(NULL),
-
m_OKButton(this),m_CancelButton(this), m_DBName(databaseName), m_DBTableName(dataTableName), m_operator(-1)
-
{
-
//打开数据库
-
m_db = QSqlDatabase::addDatabase("QSQLITE");
-
m_db.setDatabaseName(QApplication::applicationDirPath() + "/config/" + databaseName);
-
if (!m_db.open())
-
{
-
m_DBName = "";
-
m_DBTableName = "";
-
}
-
m_model = new QSqlTableModel(this, m_db);
-
m_model->setTable(m_DBTableName);
-
m_model->setEditStrategy(QSqlTableModel::OnManualSubmit); //手动提交后才修改
-
m_model->select();
-
m_TabView = new QTableView(this);
-
m_TabView->setEditTriggers(QAbstractItemView::NoEditTriggers); //设置内容不可编辑
-
/*************关联槽函数*********************/
-
connect(&m_NewButton, SIGNAL(clicked()), this, SLOT(onNewButtonClicked()));
-
connect(&m_QueryButton, SIGNAL(clicked()), this, SLOT(onQueryButtonClicked()));
-
connect(&m_UpdateButton, SIGNAL(clicked()), this, SLOT(onUpdateButtonClicked()));
-
connect(&m_DeleteButton, SIGNAL(clicked()), this, SLOT(onDeleteButtonClicked()));
-
connect(&m_PrimaryKeyLineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(onPrimaryKeyLineEditEmpty(const QString &)));
-
connect(m_TabView, SIGNAL(clicked(const QModelIndex &)), this, SLOT(onCurrentTableViewClicked(const QModelIndex &)));
-
connect(&m_OKButton, SIGNAL(clicked()), this, SLOT(onOKButtonClicked()));
-
connect(&m_CancelButton, SIGNAL(clicked()), this, SLOT(onCancelButtonClicked()));
-
/*************模型关联视图*******************/
-
m_TabView->setModel(m_model);
-
/*************选中行为为整行选中*************/
-
m_TabView->setSelectionBehavior(QAbstractItemView::SelectRows);
-
/*************对话框窗体初始化***************/
-
UiInit();
-
/*************对话框窗体初始化***************/
-
setFixedSize(600, 400);
-
setWindowTitle(QStringLiteral("用户管理"));
-
}
-
/**************************************************************************
-
* 函数名称:UiInit
-
* 函数功能:用户管理对话框界面初始化
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::UiInit()
-
{
-
m_PrimaryKeyLabel.setText(m_model->headerData(0, Qt::Horizontal).toString());
-
m_NewButton.setText(QStringLiteral("增长"));
-
m_QueryButton.setText(QStringLiteral("查询"));
-
m_UpdateButton.setText(QStringLiteral("修改"));
-
m_DeleteButton.setText(QStringLiteral("删除"));
-
m_UpdateButton.setEnabled(true);
-
m_OKButton.setText(QStringLiteral("肯定"));
-
m_CancelButton.setText(QStringLiteral("取消"));
-
/**************灵活增长界面右侧数据显示形式******************/
-
for(int i=0; i<m_model->columnCount(); i++)
-
{
-
m_infoLabelList.append(new QLabel(this));
-
m_infoLabelList[i]->setText(m_model->headerData(i, Qt::Horizontal).toString());
-
m_infoEditList.append(new QLineEdit(this));
-
m_infoEditList[i]->setEnabled(false);
-
}
-
m_OKButton.setEnabled(false);
-
m_CancelButton.setEnabled(false);
-
/**************灵活增长界面右侧数据显示形式 END******************/
-
QHBoxLayout *TotalHBoxLayout = new QHBoxLayout();
-
QVBoxLayout *TotalVBoxLayout = new QVBoxLayout();
-
QVBoxLayout *UserGroupVBoxLayout = new QVBoxLayout();
-
QHBoxLayout *UserEditHBoxLayout = new QHBoxLayout();
-
QHBoxLayout *UserButtonHBoxLayout = new QHBoxLayout();
-
QFormLayout *UserPrimaryKeyFormLayout = new QFormLayout();
-
QFormLayout *UserSelectFormLayout = new QFormLayout();
-
QHBoxLayout *UserSelectHBoxLayout = new QHBoxLayout();
-
QVBoxLayout *UserSelectVBoxLayout = new QVBoxLayout();
-
/*****************界面右侧group布局******************/
-
for (int i=0; i<m_infoLabelList.count(); i++)
-
{
-
UserSelectFormLayout->addRow( m_infoLabelList[i], m_infoEditList[i]);
-
}
-
UserSelectHBoxLayout->addWidget(&m_OKButton);
-
UserSelectHBoxLayout->addWidget(&m_CancelButton);
-
UserSelectVBoxLayout->addLayout(UserSelectFormLayout);
-
UserSelectVBoxLayout->addLayout(UserSelectHBoxLayout);
-
UserSelectVBoxLayout->addStretch();
-
/*****************界面右侧group布局 END******************/
-
UserPrimaryKeyFormLayout->addRow(&m_PrimaryKeyLabel, &m_PrimaryKeyLineEdit);
-
UserEditHBoxLayout->addLayout(UserPrimaryKeyFormLayout);
-
UserEditHBoxLayout->addWidget(&m_QueryButton);
-
UserEditHBoxLayout->addStretch();
-
UserButtonHBoxLayout->addWidget(&m_NewButton);
-
UserButtonHBoxLayout->addWidget(&m_UpdateButton);
-
UserButtonHBoxLayout->addWidget(&m_DeleteButton);
-
UserGroupVBoxLayout->addLayout(UserEditHBoxLayout);
-
UserGroupVBoxLayout->addLayout(UserButtonHBoxLayout);
-
m_Group.setLayout(UserGroupVBoxLayout);
-
TotalVBoxLayout->addWidget(&m_Group);
-
TotalVBoxLayout->addWidget(m_TabView);
-
TotalHBoxLayout->addLayout(TotalVBoxLayout, 3);
-
TotalHBoxLayout->addLayout(UserSelectVBoxLayout, 1);
-
setLayout(TotalHBoxLayout);
-
}
-
/**************************************************************************
-
* 函数名称:onNewUserButtonClick
-
* 函数功能:用户管理对话框界新增用户按钮槽函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onNewButtonClicked()
-
{
-
for (int i=0; i<m_infoEditList.count(); i++)
-
{
-
m_infoEditList[i]->setEnabled(true);
-
}
-
m_operator = INSERT;
-
m_OKButton.setEnabled(true);
-
m_CancelButton.setEnabled(true);
-
}
-
/**************************************************************************
-
* 函数名称:onQueryUserButtonClick
-
* 函数功能:用户管理对话框界查询用户按钮槽函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:廖明胜
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onQueryButtonClicked()
-
{
-
QString toFind = m_PrimaryKeyLineEdit.text();
-
QString ID = m_model->headerData(0, Qt::Horizontal).toString();
-
m_model->setFilter(ID + "=\'" + toFind + "\'");
-
m_model->select();
-
}
-
/**************************************************************************
-
* 函数名称:onUpdateButtonClicked
-
* 函数功能:用户管理对话框界修改用户按钮槽函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onUpdateButtonClicked()
-
{
-
int toUpdate = m_TabView->currentIndex().row();
-
QSqlRecord recode = m_model->record(toUpdate);
-
for (int i=0; i<recode.count(); i++)
-
{
-
m_infoEditList[i]->setEnabled(true);
-
m_infoEditList[i]->setText(recode.value(i).toString());
-
}
-
m_operator = UPDATE;
-
m_OKButton.setEnabled(true);
-
m_CancelButton.setEnabled(true);
-
}
-
/**************************************************************************
-
* 函数名称:onDeleteButtonClicked
-
* 函数功能:用户管理对话框界删除用户按钮槽函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onDeleteButtonClicked()
-
{
-
int toDelRow = m_TabView->currentIndex().row();
-
if (QMessageBox::Ok == QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("肯定要删除") + m_model->data(m_model->index(toDelRow, 0)).toString() + QStringLiteral("吗?"), QMessageBox::Ok|QMessageBox::No))
-
{
-
m_model->removeRow(toDelRow);
-
m_model->submitAll();
-
}
-
m_model->select();
-
}
-
/**************************************************************************
-
* 函数名称:onUserNameEditEmpty
-
* 函数功能:当m_UserNameEdit编辑框为空时,显示全部用户
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onPrimaryKeyLineEditEmpty(const QString & text)
-
{
-
if (text.isEmpty())
-
{
-
m_model->setTable(m_DBTableName); //从新关联数据库表,这样才能查询整个表
-
m_model->select();
-
}
-
}
-
/**************************************************************************
-
* 函数名称:onCurrentTableViewActived
-
* 函数功能:m_TableView视图选取当前行槽函数,内容映射到右侧用户编辑中
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onCurrentTableViewClicked(const QModelIndex & index)
-
{
-
if (!m_OKButton.isEnabled() || (INSERT == m_operator)) //只有可编辑而且操做为修改操做时才映射内容
-
{
-
return;
-
}
-
int currentRow = index.row();
-
QSqlRecord recode = m_model->record(currentRow);
-
for (int i=0; i<recode.count(); i++)
-
{
-
m_infoEditList[i]->setEnabled(true);
-
m_infoEditList[i]->setText(recode.value(i).toString());
-
}
-
}
-
/**************************************************************************
-
* 函数名称:onOKButtonClicked
-
* 函数功能:OKButton点击槽函数,肯定修改数据库
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onOKButtonClicked()
-
{
-
for (int i=0; i<m_infoEditList.count(); i++)
-
{
-
if (m_infoEditList[i]->text().isEmpty())
-
{
-
QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("请将内容填写完整"), QMessageBox::Ok);
-
return;
-
}
-
}
-
switch (m_operator)
-
{
-
case INSERT:
-
{
-
if (QMessageBox::Ok == QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("请肯定是否增长"), QMessageBox::Ok|QMessageBox::No))
-
{
-
int col = m_model->columnCount();
-
int row = m_model->rowCount();
-
m_model->insertRow(row);
-
for (int i=0; i<col; i++)
-
{
-
m_model->setData(m_model->index(row, i), m_infoEditList[i]->text());
-
}
-
m_model->submitAll(); //提交修改
-
}
-
}
-
break;
-
case UPDATE:
-
{
-
if (QMessageBox::Ok == QMessageBox::warning(this, QStringLiteral("提示"), QStringLiteral("请肯定是否修改"), QMessageBox::Ok|QMessageBox::No))
-
{
-
int col = m_model->columnCount();
-
int CurrentRow = m_TabView->currentIndex().row();
-
for (int i=0; i<col; i++)
-
{
-
m_model->setData(m_model->index(CurrentRow, i), m_infoEditList[i]->text());
-
}
-
m_model->submitAll(); //提交修改
-
}
-
}
-
break;
-
default:
-
break;
-
}
-
for (int i=0; i<m_infoEditList.count(); i++)
-
{
-
m_infoEditList[i]->setText("");
-
m_infoEditList[i]->setEnabled(false);
-
}
-
m_model->select();
-
m_OKButton.setEnabled(false);
-
m_CancelButton.setEnabled(false);
-
}
-
/**************************************************************************
-
* 函数名称:onCancelButtonClicked
-
* 函数功能:OKButton点击槽函数,不操做
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
void KSDemoDlg::onCancelButtonClicked()
-
{
-
for (int i=0; i<m_infoEditList.count(); i++)
-
{
-
m_infoEditList[i]->setText("");
-
m_infoEditList[i]->setEnabled(false);
-
}
-
m_OKButton.setEnabled(false);
-
m_CancelButton.setEnabled(false);
-
}
-
/**************************************************************************
-
* 函数名称:~KsUserManageDlg
-
* 函数功能:用户管理对话框析构函数
-
* 输入参数:无
-
* 输出参数:无
-
* 返回数值:void
-
* 建立人员:
-
* 建立时间:2017-11-15
-
* 修改人员:
-
* 修改时间:
-
**************************************************************************/
-
KSDemoDlg::~KSDemoDlg()
-
{
-
qDebug() << "KSDemoDlg::~KSDemoDlg()";
-
m_db.close();
-
}
main函数
-
#include "KsTestDemo.h"
-
#include <QtWidgets/QApplication>
-
#include <QCoreApplication>
-
#include "KSDemoDlg.h"
-
int main(int argc, char *argv[])
-
{
-
QApplication a(argc, argv);
-
KSDemoDlg dlg("CONFIG.db", "T_USER_MANAGE"); //这里咱们在生成KSDemoDlg类的时候,在构造函数中传入sqlite数据库名CONFIG.DB和想要操做的表T_USER_MANAGE
-
dlg.show(); //显示一下就OK
-
return a.exec();
-
}
上边的 KSDemoDlg dlg("CONFIG.db", "T_USER_MANAGE");数据库名跟表也能够换成其余的,代码通用。