Qt provides the QtSql module to provide platform-independent SQL-based database operations. What we mean by “platform
independent” includes not only operating system platforms, but also various database platforms. Qt supports the following types of databases:< /span>
- QT comes with SQLITE database , No need to install again
- QTDS has been moved since Qt4.7 Except
1.QtSql
To use the QtSql module, you need to add this sentence to the .pro file:
QT += sql
2.QSqlDatabase< /p>
QSqlDatabase class provides an interface for To access data through a connection. An instance of QSqlDatabase represents a connection. The connection provides access to the database through one of the supported database drivers, which is derived from QSqlDriver.
2.1 An example of creating a database is as follows< /span>
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("scooters.dat"); //If this directory If there is no such file, it will be generated in this directory, otherwise link to the file
if (!db.open()) {
QMessageBox::warning(0, QObject::tr("< /span>Database Error" ),
db.lastError().text());
return false;
}
After compiling and running, you can see that the file has been created :
After successful creation, the file the default is empty, and then you can use the QSqlQuery class to operate the database, the QSqlQuery class uses SQL statements, if you only need to use high-level data< /span>
library interface (do not care about SQL syntax), we can choose QSqlTableModel and
QSqlRelationalTableModel(introduced in subsequent chapters). In this chapter, we introduce QSqlQuery class, how to use SQL syntax.
3.QSqlQueryClass introduction
through the exec() member function< /span> to execute DML (data manipulation language) statements, such as SELECT, INSERT, UPDATE and DELETE, and DDL (data definition language) statements, etc..
For example:
QSqlQuery query;
query.exec("DROP TABLE students"); //Delete the name Students’ table
4. Next , Let’s talk about how to import data
Create a table:
query.exec("CREATE TABLE students ("
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
" score INTEGER NOT NULL, "
"class VARCHAR(40) NOT NULL)");
//Create a students table with the titles id, name, score, class
” PRIMARY KEY AUTOINCREMENT ,”: means that the column is an integer increment, if it is empty, it will automatically fill in 1, and then each row below will automatically +1, PRIMARY KEY means that this column is used as the primary key of the list, It can easily get a row of data
” INTEGER “: means the column is a signed integer
” VARCHAR(40) “: means that the column is a variable-length character string, by default it can only store English and numbers or utf-8, up to Store 40 bytes.
“NOT NULL “: means that the content of the column is not empty
< span style="color: #800000; font-size: 15px;">Import data:
query.exec( "INSERT INTO students (name, score,class) "
"VALUES ('小张', 85,'Early 2-1 class') ");
//to (name, score,class) in the students table Insert a piece of data under the heading "小张", 85, "Early 2-1 class"
after adding As shown in the figure below:
5. Import libraries in bulk
If we need a large string of data When importing, you can also use prepare() to bind the value, and then use bindValue()Add data to the bound value
The sample code is as follows:
QStringList names;
names<<"Small A"<<"Little B "<<"Small C "<<"Little D"<<"Little E"<<"Little F"<<" span>Little G"
<<"Little H"<<"Little I"<<"Little G< span style="color: #800000;">"<<"小K< /span>"<<"Small L"<<"Little M"<<"Little N";
QStringList clases;
clases<<"First 1-1 class< span style="color: #800000;">"<<"初1- Class 2"<<"Early 1-3 classes"<<"< span style="color: #800000;">First 2-1 class"
<<"Early 2-2 class"<<"Early 2-3 classes"<<"Early Class 3-1"<<"Beginning Class 3-2"<<"Beginning Class 3-3";
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE ");
db.setDatabaseName("students.dat"); //In this directory Generate below
QSqlQuery query;
query.exec("DROP TABLE students"); //Clear it first Table
query.exec("CREATE TABLE students (< span style="color: #800000;">"
"id INTEGER PRIMARY KEY AUTOINCREMENT, "
"name VARCHAR(40) NOT NULL, "
" score INTEGER NOT NULL, "
"class VARCHAR(40) NOT NULL)");
//Create a students table
query.prepare("INSERT INTO students (name, score,class ) "
"VALUES (:name, :score, :class)");
//Add binding values for each column header
foreach (QString name, names) //Get each name from the names table
{
query.bindValue(":name", name); //to tie Add the name to the fixed value
query.bindValue(":score", (qrand()% 101)); //Achievements
query.bindValue(":class", clases[qrand()%clases.length()] ); //Class
query.exec(); //Add to the library
}
After running, open students.dat through SQLite tool, as shown below:< /span>
6. Inquiry form content
We are right The students.dat file generated in the above figure is used to query the content, you need to use WHERE strong> Keyword implementation.
Example -Query students whose score value is between 60 and 80:
query.exec("SELECT * FROM students WHERE score >= 60 AND score <= 80;");
while(query.next())
{
QString id = query.value(0).toString();
QString name = query.value(1).toString();
QString score = query.value(2).toString();
QString classs = query.value(3).toString();
qDebug()<classs;
}
Run printing:
Of course there are other sentences, such as: p>
"SELECT * FROM students WHERE score >= 80 OR class =='Early Class 3-3';"
//The judgement score is greater than or equal to 80, or the class is junior 3-3 class< /span>
Print as shown below:
"SELECT * FROM students WHERE class GLOB'*3-3*';< /span>"
// GLOB stands for wildcard, matching class names with "3-3"< /span>
Print as shown below:
7. Delete table content
< p>There are 3 sentences to delete table content:
- DROP: It is used to delete the entire table, and the table structure will also be deleted. After deletion, you can only use CREATE TABLE to recreate Table
- TRUNCATE: There is no such statement in SQLite, but in MySQL, it is used to clarify the data in the table, but the table structure will not be deleted.
- DELETE: Delete some records, and the table structure will not be deleted, the deletion speed is slower than the above two statements, you can cooperate WHERE to delete a specified row
query.exec("DELETE FROM students"); //Delete all in the students table Content
After deleting, it will look like the picture below:
Example 2-Delete a line with id=3
< div class="code">
query.exec("DELETE FROM students WHERE id = 3 ");