当前位置:网站首页>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();
}
边栏推荐
- Essential characteristics of convolution operation +textcnn text classification
- 杰理之获取复位源和唤醒的 IO 口的方法【篇】
- 微信小程序报错:request:fail url not in domain list
- 使用DiskGenius拓展系统盘C盘的容量
- Vscode automatically generates ifndef define ENDIF of header file
- Vscode / * * generate function comments
- golang sort slice int
- Deeply understand and grasp the basic characteristics of digital economy
- golang list to string
- Swagger实现后台接口自动化文档
猜你喜欢

Under the same WiFi, the notebook is connected to the virtual machine on the desktop

什么是算子?

Unity technical manual - size over lifetime and size by speed

杰理之如何给外界输出一个时钟源使用【篇】

WARNING: Unsupported upgrade request.

Unity technical manual - lifecycle rotation rotationoverlifetime speed rotation rotationbyspeed external forces

How to solve the problem of network disconnection after enabling hotspot sharing in win10?
![[tips] how to quickly start a new position for a new software testing engineer](/img/88/5c002f492db56c646cbfd1ee98cd5b.png)
[tips] how to quickly start a new position for a new software testing engineer

利用Qt制作美化登录界面框

DDD concept is complex and difficult to understand. How to design code implementation model in practice?
随机推荐
视频制作素材网站整理
Precautions for use of Jerry's SPI slave [chapter]
Huawei cloud gaussdb (for redis) unveiling issue 19: gaussdb (for redis) comprehensive comparison with CODIS
Essential characteristics of convolution operation +textcnn text classification
CGI connects to database through ODBC
About Equilibrium - Simplified bottleneck model
Swagger implements background interface automation document
golang sort slice int
[matlab] data statistical analysis
[compilation principle] overview
Time series analysis of data mining [easy to understand]
Use of jupyter
[UVM practice== > episode_1] ~ MCDF design update, AMBA standard interface, UVM verification environment update
Is Guotai Junan Securities reliable? Is it legal? Is it safe to open a stock account?
Distributed remote management of distribution room environment
College Students' hot summer exchange, Rog star product phantom 16 flipped version / phantom 13 / phantom x appointment
Indexes
[UVM practice== > episode_2] ~ VIP, VIP development, VIP release
Golang sort slice int
BILSTM和CRF的那些事