Qt中使用SQLite數據庫
標簽: QT
前言
SQLite(sql)是一款開源輕量級的數據庫軟件,不需要server,可以集成在其他軟件中,非常適合嵌入式系統。
Qt5以上版本可以直接使用SQLite(Qt自帶驅動)。
用法
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
。如果需要使用自定義的連接名稱(如果程序需要處理多個數據庫文件的話就會這樣),則應該加入第二個參數,例如
database = QSqlDatabase::addDatabase("QSQLITE", "my_sql_connection);
這個時候,如果在另一個地方需要判斷my_sql_connection
連接是否存在,就應該使用if (QSqlDatabase::contains("my_sql_connection"))
。
(4)else
分支第二行中,setDatabaseName()
的參數是數據庫文件名。如果這個數據庫不存在,則會在后續操作時自動創建;如果已經存在,則后續的操作會在已有的數據庫上進行。
(5)else
分支后面兩行,設置用戶名和密碼。用戶名,密碼都可以隨便取,也可以省略。
2. 打開數據庫
使用open()
打開數據庫,并判斷是否成功。注意,在第一步檢查連接是否存在時,如果連接存在,則在返回這個連接的時候,會默認將數據庫打開。
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,第二列是名字,第三列是年齡。
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()
函數的參數中,例如:
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()
執行成功,則創建表格成功。
例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數據庫。
1、首先使用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***********************/
編譯輸出:
2、使用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();
-
}
編譯運行一下:
3、最后使用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");數據庫名跟表也可以換成其他的,代碼通用。
智能推薦
freemarker + ItextRender 根據模板生成PDF文件
1. 制作模板 2. 獲取模板,并將所獲取的數據加載生成html文件 2. 生成PDF文件 其中由兩個地方需要注意,都是關于獲取文件路徑的問題,由于項目部署的時候是打包成jar包形式,所以在開發過程中時直接安照傳統的獲取方法沒有一點文件,但是當打包后部署,總是出錯。于是參考網上文章,先將文件讀出來到項目的臨時目錄下,然后再按正常方式加載該臨時文件; 還有一個問題至今沒有解決,就是關于生成PDF文件...
電腦空間不夠了?教你一個小秒招快速清理 Docker 占用的磁盤空間!
Docker 很占用空間,每當我們運行容器、拉取鏡像、部署應用、構建自己的鏡像時,我們的磁盤空間會被大量占用。 如果你也被這個問題所困擾,咱們就一起看一下 Docker 是如何使用磁盤空間的,以及如何回收。 docker 占用的空間可以通過下面的命令查看: TYPE 列出了docker 使用磁盤的 4 種類型: Images:所有鏡像占用的空間,包括拉取下來的鏡像,和本地構建的。 Con...
requests實現全自動PPT模板
http://www.1ppt.com/moban/ 可以免費的下載PPT模板,當然如果要人工一個個下,還是挺麻煩的,我們可以利用requests輕松下載 訪問這個主頁,我們可以看到下面的樣式 點每一個PPT模板的圖片,我們可以進入到詳細的信息頁面,翻到下面,我們可以看到對應的下載地址 點擊這個下載的按鈕,我們便可以下載對應的PPT壓縮包 那我們就開始做吧 首先,查看網頁的源代碼,我們可以看到每一...
猜你喜歡
Linux C系統編程-線程互斥鎖(四)
互斥鎖 互斥鎖也是屬于線程之間處理同步互斥方式,有上鎖/解鎖兩種狀態。 互斥鎖函數接口 1)初始化互斥鎖 pthread_mutex_init() man 3 pthread_mutex_init (找不到的情況下首先 sudo apt-get install glibc-doc sudo apt-get install manpages-posix-dev) 動態初始化 int pthread_...
統計學習方法 - 樸素貝葉斯
引入問題:一機器在良好狀態生產合格產品幾率是 90%,在故障狀態生產合格產品幾率是 30%,機器良好的概率是 75%。若一日第一件產品是合格品,那么此日機器良好的概率是多少。 貝葉斯模型 生成模型與判別模型 判別模型,即要判斷這個東西到底是哪一類,也就是要求y,那就用給定的x去預測。 生成模型,是要生成一個模型,那就是誰根據什么生成了模型,誰就是類別y,根據的內容就是x 以上述例子,判斷一個生產出...
styled-components —— React 中的 CSS 最佳實踐
https://zhuanlan.zhihu.com/p/29344146 Styled-components 是目前 React 樣式方案中最受關注的一種,它既具備了 css-in-js 的模塊化與參數化優點,又完全使用CSS的書寫習慣,不會引起額外的學習成本。本文是 styled-components 作者之一 Max Stoiber 所寫,首先總結了前端組件化樣式中的最佳實踐原則,然后在此基...
19.vue中封裝echarts組件
19.vue中封裝echarts組件 1.效果圖 2.echarts組件 3.使用組件 按照組件格式整理好數據格式 傳入組件 home.vue 4.接口返回數據格式...