当前位置:网站首页>QT using SQLite database
QT using SQLite database
2022-06-25 17:50:00 【Autodesk_ Glodon】
1、 initialization
void Widget::InitialSQLiteDb()
{
QSqlDatabase m_dbSystemData ;
// Check the connected mode - Default connection name
// QSqlDatabase::contains(QSqlDatabase::defaultConnection)
// if(QSqlDatabase::contains("qt_sql_default_connection"))
// {
// db = QSqlDatabase::database("qt_sql_default_connection");
// }
// else
// {
// db = QSqlDatabase::addDatabase("QSQLITE");
// }
// Check the connected mode - Custom connection name
if(QSqlDatabase::contains("mysql_connection"))
{
m_dbSystemData = QSqlDatabase::database("mysql_connection");
}
else
{
m_dbSystemData = QSqlDatabase::addDatabase("QSQLITE","mysql_connection");
}
// Set the database path , Create if it does not exist
m_dbSystemData.setDatabaseName("mySysData.db");
//db.setUserName();
// Open database
if(!m_dbSystemData.open())
{
qDebug()<<"create sqldb failed!";
return;
}
// Close the database
m_dbSystemData.close();
}
2、 Create a table
void Widget::CreateTable()
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return;
}
// Create... If it doesn't exist my_table surface id Self increasing ,name only
const QString sql=R"( CREATE TABLE IF NOT EXISTS my_table ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, code INTEGER, name CHAR (50) UNIQUE NOT NULL, age INTEGER, sex INTEGER, score INTEGER, rank INTEGER, address CHAR (50) );)";
//QSqlQuery Pre tectonic , need db Opened and connected ; Not specified db perhaps db Use the default connection when it is invalid
QSqlQuery query(m_dbSystemData);
if(query.exec(sql))
{
qDebug()<<"create table success!";
}
else
{
// Print sql Statement error message
qDebug()<<"create table error!"<< query.lastError();
}
}
3、 insert data
void Widget::insertRecord(const QString &name, const QString address, int code, int age, int sex, int score, int rank)
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return;
}
qDebug()<<"2222!";
QSqlQuery query(m_dbSystemData);
// Mode one , Direct execution SQL sentence
query.exec(QString(R"(INSERT INTO my_table(code,name,age,sex,score,rank,address) VALUES(%1,'%2',%3,%4,%5,%6,'%7');)")
.arg(code).arg(name).arg(age).arg(sex).arg(score).arg(rank).arg(address));
// Mode two , Binding value , Undetermined variables are occupied by question marks by default , Notice that the string also has no quotation marks
/*query.prepare(R"(INSERT INTO my_table(name,age) VALUES(?,?);)"); query.addBindValue(name); query.addBindValue(age); query.exec();*/
}
4、 Delete data
void Widget::deleteRecord(const QString &name)
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return;
}
QSqlQuery query(m_dbSystemData);
// Mode one , Direct execution SQL sentence
query.exec(QString(R"(DELETE FROM my_table WHERE name='%1';)").arg(name));
// Mode two , Binding value , Undetermined variables are occupied by question marks by default
/*query.prepare(R"(DELETE FROM my_table WHERE name=?;)"); query.addBindValue(name); query.exec();*/
}
5、 Update data
void Widget::updateRecord(const QString &name, int age)
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return;
}
QSqlQuery query(m_dbSystemData);
// Mode one , Direct execution SQL sentence
query.exec(QString(R"(UPDATE my_table SET age=%2 WHERE name='%1';)")
.arg(name).arg(age));
// Mode two , Binding value , Pending variable default question mark , Customizable
/*query.prepare(R"(UPDATE my_table SET age=:age WHERE name=:name;)"); query.bindValue(":name",name);// Replace with a custom alias query.bindValue(":age",age); query.exec();*/
}
6、 Query data
int Widget::searchRecord(const QString &name)
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return -1;
}
QSqlQuery query(m_dbSystemData);
query.exec(QString(R"(SELECT age FROM my_table WHERE name='%1';)").arg(name));
// Get the... Of query results 0 It's worth ,
// If the result is multiple rows of data , You can use while(query.next()){} Go through every line
int ageValue=-1;
if(query.next())
{
ageValue = query.value(0).toInt();
}
qDebug()<<"age value is: "<< ageValue;
return ageValue;
}
7、 Initialize table data
void Widget::InitialQTable()
{
if(!m_dbSystemData.isOpen())
{
qDebug()<<"db is not open!";
return;
}
ui->tableWidget->setColumnCount(7);
//ui->tableWidget->setRowCount(10);
ui->tableWidget->verticalHeader()->setVisible(false); // Hide the list header
ui->tableWidget->horizontalHeader()->setStretchLastSection(true);
ui->tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows); // The way the whole line is selected
QStringList header;
header<<" Student number "<<" full name "<<" Age "<<" Gender "<<" Total score "<<" ranking "<<" Address ";
ui->tableWidget->setHorizontalHeaderLabels(header);
QSqlQuery query(m_dbSystemData);
query.exec("SELECT * FROM my_table");
// If the result is multiple rows of data , You can use while(query.next()){} Go through every line
int nRow = 0;
while(query.next())
{
int iRow = ui->tableWidget->rowCount();
ui->tableWidget->setRowCount(iRow + 1);
int id = query.value(0).toInt();
QString code = query.value(1).toString();
QString name = query.value(2).toString();
QString age = query.value(3).toString();
int nSex = query.value(4).toInt();
QString sex;
if(nSex == 0)
{
sex = " male ";
}
else
{
sex = " Woman ";
}
QString score = query.value(5).toString();
QString rank = query.value(6).toString();
QString address = query.value(7).toString();
qDebug()<< id << code << name << age << sex << score << rank;
ui->tableWidget->setItem(nRow,0,new QTableWidgetItem(code));
ui->tableWidget->setItem(nRow,1,new QTableWidgetItem(name));
ui->tableWidget->setItem(nRow,2,new QTableWidgetItem(age));
ui->tableWidget->setItem(nRow,3,new QTableWidgetItem(sex));
ui->tableWidget->setItem(nRow,4,new QTableWidgetItem(score));
ui->tableWidget->setItem(nRow,5,new QTableWidgetItem(rank));
ui->tableWidget->setItem(nRow,6,new QTableWidgetItem(address));
nRow++;
}
ui->tableWidget->show();
}
边栏推荐
- What is public chain development? What are the public chain development projects?
- 【 NLP 】 in this year's English college entrance examination, CMU delivered 134 high scores with reconstruction pre training, significantly surpassing gpt3
- Assembly language (6) uses JCC instructions to construct branches and loops
- Getting started with kotlin (20) several common dialog boxes
- IDEA全局搜索汉字[通俗易懂]
- VSCode /**生成函数注释
- Hover effect of eight buttons
- Introduction to the container of() function
- 一些常用的知识点积累
- 使用DiskGenius拓展系統盤C盤的容量
猜你喜欢
The Stackies 2022:32个营销技术栈入选
Precautions for the use of Jerry's wake-up mouth [chapter]
有关均衡----简易版瓶颈模型
[compilation principle] lexical analysis
杰理之增加加密文件播放功能【篇】
【日常记录】——对BigDecimal除法运算时遇到的Bug
匯編語言(5)寄存器(內存訪問)
Introduction to the container of() function
杰理之系统时钟设置出现复位或无效问题【篇】
Operating steps for installing CUDA in win10 (continuous improvement)
随机推荐
CGI connects to database through ODBC
College Students' hot summer exchange, Rog star product phantom 16 flipped version / phantom 13 / phantom x appointment
RuntimeError: Trying to backward through the graph a second time (or directly access saved variable
CVPR small target detection: context and attention mechanisms improve small target detection (attached with paper Download)
golang sort slice int
杰理之唤醒口使用注意事项【篇】
How Jerry used to output a clock source to the outside world [chapter]
Acy100 oil fume concentration online monitor for kitchen oil fume emission in catering industry
Kotlin入门(20)几种常见的对话框
BILSTM和CRF的那些事
Unity technical manual - size over lifetime and size by speed
SDN系统方法 | 10. SDN的未来
mysql mysql-8.0.19-winx64 安装与navicat连接
Precautions for using Jerry's timer [chapter]
[machine learning] case study of college entrance examination prediction based on multiple time series
DDD concept is complex and difficult to understand. How to design code implementation model in practice?
十大证券公司哪个佣金最低 办理开户安全吗
lock
Time series analysis of data mining [easy to understand]
卷积操作的本质特性+TextCNN文本分类