sqlite and QT database programming operations

Table of contents

Table of contents

1.sqlite installation

2.sqlite basic data types

1. Rules for determining field affinity:

2. Specific examples:

3.sqlite basic operations

1. Creation of table

2.Delete table

3. Insert data

4. Query table data

5. Modify table data

6. Delete table data

7. Conditional judgment

8.sqlite operator

 9.sqlite expression

1. Boolean expression:

2. Numerical expression:

3.Date expression:

 10. Add WHERE to SQLite’s deletion and modification check conditions

1. Query conditional statement

2. Modify the conditional statement:

3. Delete the conditional statement:

11.Like Glob Limit Order Group Having Distinct

1.LIKE

2.Glob

3. LIMIT clause and OFFSET clause

4. Order By

5.Group By

6.Having clause

7.Distinct 

4.sqlite reference materials

5.QT operates sqlite

1 Overview

2.Qt database related classes

3. Layering of database classes

4. Use of database classes


1.sqlite installation

        Go to the SQLite Download Page to download sqlite-tools-win32-x86-3390400.zip , unzip it and open it. Use the .help command to view the point commands supported by sqlite. There is a detailed description of the point commands in SQLite Command | Rookie Tutorial .

        Commonly used point commands:

.show

1. Open the header display 

 .header on

2. Turn on column mode

.mode column

3. Display running timestamp

.timer on

4.Create database

.open test.db

5. Command to view the created table (demo is the table name)

.schema demo

 The above is a brief explanation of the dot command provided by the sqlite software. This is not the same type of command as the sql command. SQL commands end with semicolon;.

2.sqlite basic data types

     NULL: Indicates that the value is NULL.
     INTEGER: Unsigned integer value.
     REAL: Floating point value.
     TEXT: Text string, the encoding used for storage is UTF-8, UTF-16BE, UTF-16LE.
     BLOB: Stores Blob data. This type of data is exactly the same as the input data.

Type Affinity can be used when declaring generated tables:

        In order to maximize data type compatibility between SQLite and other database engines, SQLite proposes the concept of "Type Affinity". We can understand "type affinity" like this. After a table field is declared, SQLite will select an affinity type for it based on the type when the field is declared. When data is inserted, the data in this field will preferentially use the affinity type as the The way the value is stored, unless the related type does not match or the current data cannot be converted to the related type, then SQLite will consider other types that are more suitable for the value to store the value. The current version of SQLite supports the following five affinity types:

Kind of relationship describe  
TEXT Before numeric data can be inserted, it needs to be converted to text format and then inserted into the target field.
NUMERIC When text data is inserted into a field with an affinity of NUMERIC, if the conversion operation does not cause the loss of data information and is completely reversible, then SQLite will convert the text data into INTEGER or REAL type data. If the conversion fails, SQLite The data will still be stored as TEXT. For new data of type NULL or BLOB, SQLite will not perform any conversion and store the data directly as NULL or BLOB. Additional explanation is that for constant text in floating point format, such as "30000.0", if the value can be converted to INTEGER without losing the numerical information, then SQLite will convert it to the INTEGER storage method.
INTEGER For fields whose affinity type is INTEGER, the rules are the same as NUMERIC. The only difference is when executing CAST expressions.
REAL The rules are basically the same as NUMERIC. The only difference is that text data such as "30000.0" will not be converted into INTEGER storage mode.
NONE Without any conversion, the data is stored directly in the data type to which the data belongs.

1. Rules for determining field affinity:

    The affinity of a field is determined based on the type defined when the field is declared. For specific rules, please refer to the following list. What needs to be noted is the order of the following list, that is, if a certain field type meets both affinities, the rule listed first will take effect first.
    1). If the type string contains "INT", then the related type of the field is INTEGER.
    2). If the type string contains "CHAR", "CLOB" or "TEXT", then the related type of the field is TEXT, such as VARCHAR.
    3). If the type string contains "BLOB", then the affinity type of the field is NONE.
    4). If the type string contains "REAL", "FLOA" or "DOUB", then the related type of the field is REAL.
    5). In other cases, the affinity type of the field is NUMERIC.

    2. Specific examples:

Declaration type Kind of relationship Apply rules
INT
INTEGER
TINYINT
SMALLINT
MEDIUMINT
BIGINT
UNSIGNED BIG INT
INT2
INT8
INTEGER 1
CHARACTER(20)
VARCHAR(255)
VARYING CHARACTER(255)
NCHAR(55)
NATIVE CHARACTER(70)
NVARCHAR(100)
TEXT
CLOB
TEXT 2
BLOB NONE 3
REAL
DOUBLE
DOUBLE PRECISION
FLOAT
REAL 4
NUMERIC
DECIMAL(10,5)
BOOLEAN
DATE
DATETIME
NUMERIC 5

        Note: In SQLite, the length information 255 of type VARCHAR(255) has no practical meaning, just to ensure consistency with the declaration of other databases.

3.sqlite basic operations

1. Creation of table

CREATE TABLE DEMO(ID INT,D1_D7 TEXT,TIME TEXT,TYPE TEXT);

2.Delete table

DROP TABLE DEMO;

3. Insert data

INSERT INTO DEMO VALUES(12345,'A1A2A3A4A5A6A7A8','2022-01-01 10-09-21.567','EXT');
--用一个表填充另外一个表
INSERT INTO first_table_name [(column1, column2, ... columnN)] 
   SELECT column1, column2, ...columnN 
   FROM second_table_name
   [WHERE condition];

 4. Query table data

SELECT * FROM DEMO;

5. Modify table data

UPDATE DEMO SET ID = 75;

6. Delete table data

DELETE FROM DEMO;

 7. Conditional judgment

You can add conditional judgments WHERE when adding, deleting or modifying table lookup statements. SQLite's conditional statements must match expressions or operators.

8.sqlite operator

operator describe Example
+ Addition - Add the values ​​on both sides of the operator a + b will get 30
- Subtraction - left operand minus right operand a - b will get -10
* Multiplication - Multiply the values ​​on both sides of the operator a * b will get 200
/ Division - divides the left operand by the right operand b / a will get 2
% Modulo - the remainder obtained after dividing the left operand by the right operand b % a will give 0
operator describe Example
== Checks whether the values ​​of two operands are equal, if so then the condition is true. (a == b) is not true.
= Checks whether the values ​​of two operands are equal, if so then the condition is true. (a = b) is not true.
!= Checks whether the values ​​of two operands are equal, if not then the condition becomes true. (a != b) is true.
<> Checks whether the values ​​of two operands are equal, if not then the condition becomes true. (a <> b) is true.
> 检查左操作数的值是否大于右操作数的值,如果是则条件为真。 (a > b) 不为真。
< 检查左操作数的值是否小于右操作数的值,如果是则条件为真。 (a < b) 为真。
>= 检查左操作数的值是否大于等于右操作数的值,如果是则条件为真。 (a >= b) 不为真。
<= 检查左操作数的值是否小于等于右操作数的值,如果是则条件为真。 (a <= b) 为真。
!< 检查左操作数的值是否不小于右操作数的值,如果是则条件为真。 (a !< b) 为假。
!> 检查左操作数的值是否不大于右操作数的值,如果是则条件为真。 (a !> b) 为真。
运算符 描述
AND AND 运算符允许在一个 SQL 语句的 WHERE 子句中的多个条件的存在。
BETWEEN BETWEEN 运算符用于在给定最小值和最大值范围内的一系列值中搜索值。
EXISTS EXISTS 运算符用于在满足一定条件的指定表中搜索行的存在。
IN IN 运算符用于把某个值与一系列指定列表的值进行比较。
NOT IN IN 运算符的对立面,用于把某个值与不在一系列指定列表的值进行比较。
LIKE LIKE 运算符用于把某个值与使用通配符运算符的相似值进行比较。
GLOB GLOB 运算符用于把某个值与使用通配符运算符的相似值进行比较。GLOB 与 LIKE 不同之处在于,它是大小写敏感的。
NOT NOT 运算符是所用的逻辑运算符的对立面。比如 NOT EXISTS、NOT BETWEEN、NOT IN,等等。它是否定运算符。
OR OR 运算符用于结合一个 SQL 语句的 WHERE 子句中的多个条件。
IS NULL NULL 运算符用于把某个值与 NULL 值进行比较。
IS IS 运算符与 = 相似。
IS NOT IS NOT 运算符与 != 相似。
|| 连接两个不同的字符串,得到一个新的字符串。
UNIQUE UNIQUE 运算符搜索指定表中的每一行,确保唯一性(无重复)。

运算符 描述 实例
& 如果同时存在于两个操作数中,二进制 AND 运算符复制一位到结果中。 (A & B) 将得到 12,即为 0000 1100
| 如果存在于任一操作数中,二进制 OR 运算符复制一位到结果中。 (A | B) 将得到 61,即为 0011 1101
~ 二进制补码运算符是一元运算符,具有"翻转"位效应,即0变成1,1变成0。 (~A ) 将得到 -61,即为 1100 0011,一个有符号二进制数的补码形式。
<< 二进制左移运算符。左操作数的值向左移动右操作数指定的位数。 A << 2 将得到 240,即为 1111 0000
>> 二进制右移运算符。左操作数的值向右移动右操作数指定的位数。 A >> 2 将得到 15,即为 0000 1111

 9.sqlite表达式

SELECT column1, column2, columnN 
FROM table_name 
WHERE [CONDITION | EXPRESSION];

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0

 1.布尔表达式:

SELECT * FROM COMPANY WHERE SALARY = 10000;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
4           James        24          Houston   10000.0

2.数值表达式:

SELECT (15 + 6) AS ADDITION
ADDITION = 21

3.日期表达式:

SELECT CURRENT_TIMESTAMP;

 10.sqlite的删改查条件添加 WHERE

1. 查询条件语句

SELECT column1, column2, columnN 
FROM table_name
WHERE [condition]

 查询条件例子

 SELECT * FROM COMPANY WHERE AGE >= 25 AND SALARY >= 65000;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0

2.修改条件语句:

UPDATE table_name
SET column1 = value1, column2 = value2...., columnN = valueN
WHERE [condition];

3.删除条件语句:

DELETE FROM table_name
WHERE [condition];

11.Like Glob Limit Order Group Having Distinct

1.LIKE

SQLite 的 LIKE 运算符是用来匹配通配符指定模式的文本值。如果搜索表达式与模式表达式匹配,LIKE 运算符将返回真(true),也就是 1。这里有两个通配符与 LIKE 运算符一起使用:

  • 百分号 (%)

  • 下划线 (_)

        百分号(%)代表零个、一个或多个数字或字符。下划线(_)代表一个单一的数字或字符。这些符号可以被组合使用。

语法说明:

SELECT column_list 
FROM table_name
WHERE column LIKE 'XXXX%'


SELECT column_list 
FROM table_name
WHERE column LIKE '%XXXX%'

SELECT column_list 
FROM table_name
WHERE column LIKE 'XXXX_'


SELECT column_list 
FROM table_name
WHERE column LIKE '_XXXX'


SELECT column_list 
FROM table_name
WHERE column LIKE '_XXXX_'

        这里可以使用 AND 或 OR 运算符来结合 N 个数量的条件。在这里,XXXX 可以是任何数字或字符串值。

例子:

语句 描述
WHERE SALARY LIKE '200%' 查找以 200 开头的任意值
WHERE SALARY LIKE '%200%' 查找任意位置包含 200 的任意值
WHERE SALARY LIKE '_00%' 查找第二位和第三位为 00 的任意值
WHERE SALARY LIKE '2_%_%' 查找以 2 开头,且长度至少为 3 个字符的任意值
WHERE SALARY LIKE '%2' 查找以 2 结尾的任意值
WHERE SALARY LIKE '_2%3' 查找第二位为 2,且以 3 结尾的任意值
WHERE SALARY LIKE '2___3' 查找长度为 5 位数,且以 2 开头以 3 结尾的任意值

2.Glob

SQLite 的 GLOB 运算符是用来匹配通配符指定模式的文本值。如果搜索表达式与模式表达式匹配,GLOB 运算符将返回真(true),也就是 1。与 LIKE 运算符不同的是,GLOB 是大小写敏感的,对于下面的通配符,它遵循 UNIX 的语法。

  • 星号 (*)

  • 问号 (?)

星号(*)代表零个、一个或多个数字或字符。问号(?)代表一个单一的数字或字符。这些符号可以被组合使用。

语法说明:

SELECT FROM table_name
WHERE column GLOB 'XXXX*'


SELECT FROM table_name
WHERE column GLOB '*XXXX*'


SELECT FROM table_name
WHERE column GLOB 'XXXX?'


SELECT FROM table_name
WHERE column GLOB '?XXXX'


SELECT FROM table_name
WHERE column GLOB '?XXXX?'


SELECT FROM table_name
WHERE column GLOB '????'

例子:

语句 描述
WHERE SALARY GLOB '200*' 查找以 200 开头的任意值
WHERE SALARY GLOB '*200*' 查找任意位置包含 200 的任意值
WHERE SALARY GLOB '?00*' 查找第二位和第三位为 00 的任意值
WHERE SALARY GLOB '2??' 查找以 2 开头,且长度至少为 3 个字符的任意值
WHERE SALARY GLOB '*2' 查找以 2 结尾的任意值
WHERE SALARY GLOB '?2*3' 查找第二位为 2,且以 3 结尾的任意值
WHERE SALARY GLOB '2???3' 查找长度为 5 位数,且以 2 开头以 3 结尾的任意值

3.  LIMIT 子句与 OFFSET 子句

带有 LIMIT 子句的 SELECT 语句的基本语法如下:

SELECT column1, column2, columnN 
FROM table_name
LIMIT [no of rows]

下面是 LIMIT 子句与 OFFSET 子句一起使用时的语法:

SELECT column1, column2, columnN 
FROM table_name
LIMIT [no of rows] OFFSET [row num]

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
 SELECT * FROM COMPANY LIMIT 6;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
SELECT * FROM COMPANY LIMIT 3 OFFSET 2;

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0

 4. Order By

SQLite 的 ORDER BY 子句是用来基于一个或多个列按升序或降序顺序排列数据。

SELECT column-list 
FROM table_name 
[WHERE condition] 
[ORDER BY column1, column2, .. columnN] [ASC | DESC];


SELECT
   select_list
FROM
   table
ORDER BY
    column_1 ASC,
    column_2 DESC;
  • ASC 默认值,从小到大,升序排列
  • DESC 从大到小,降序排列

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0

结果按 SALARY 升序排序:

SELECT * FROM COMPANY ORDER BY SALARY ASC;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
7           James       24          Houston     10000.0
2           Allen       25          Texas       15000.0
1           Paul        32          California  20000.0
3           Teddy       23          Norway      20000.0
6           Kim         22          South-Hall  45000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0

结果按 NAME 和 SALARY 升序排序:

 SELECT * FROM COMPANY ORDER BY NAME, SALARY ASC;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
2           Allen       25          Texas       15000.0
5           David       27          Texas       85000.0
7           James       24          Houston     10000.0
6           Kim         22          South-Hall  45000.0
4           Mark        25          Rich-Mond   65000.0
1           Paul        32          California  20000.0
3           Teddy       23          Norway      20000.0

结果按 NAME 降序排序:

SELECT * FROM COMPANY ORDER BY NAME DESC;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
3           Teddy       23          Norway      20000.0
1           Paul        32          California  20000.0
4           Mark        25          Rich-Mond   65000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
5           David       27          Texas       85000.0
2           Allen       25          Texas       15000.0

5.Group By

        SQLite 的 GROUP BY 子句用于与 SELECT 语句一起使用,来对相同的数据进行分组。在 SELECT 语句中,GROUP BY 子句放在 WHERE 子句之后,放在 ORDER BY 子句之前。

语法:

        下面给出了 GROUP BY 子句的基本语法。GROUP BY 子句必须放在 WHERE 子句中的条件之后,必须放在 ORDER BY 子句之前。

SELECT column-list
FROM table_name
WHERE [ conditions ]
GROUP BY column1, column2....columnN
ORDER BY column1, column2....columnN

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
SELECT NAME, SUM(SALARY) FROM COMPANY GROUP BY NAME;
NAME        SUM(SALARY)
----------  -----------
Allen       15000.0
David       85000.0
James       10000.0
Kim         45000.0
Mark        65000.0
Paul        20000.0
Teddy       20000.0

 6.Having 子句

HAVING 子句允许指定条件来过滤将出现在最终结果中的分组结果。

WHERE 子句在所选列上设置条件,而 HAVING 子句则在由 GROUP BY 子句创建的分组上设置条件。

语法:

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

        在一个查询中,HAVING 子句必须放在 GROUP BY 子句之后,必须放在 ORDER BY 子句之前。下面是包含 HAVING 子句的 SELECT 语句的语法:

       

SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
8           Paul        24          Houston     20000.0
9           James       44          Norway      5000.0
10          James       45          Texas       5000.0
SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;
ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
2           Allen       25          Texas       15000
5           David       27          Texas       85000
6           Kim         22          South-Hall  45000
4           Mark        25          Rich-Mond   65000
3           Teddy       23          Norway      20000

7.Distinct 

        SQLite 的 DISTINCT 关键字与 SELECT 语句一起使用,来消除所有重复的记录,并只获取唯一一次记录。

        有可能出现一种情况,在一个表中有多个重复的记录。当提取这样的记录时,DISTINCT 关键字就显得特别有意义,它只获取唯一一次记录,而不是获取重复记录。

语法:

SELECT DISTINCT column1, column2,.....columnN 
FROM table_name
WHERE [condition]

例子:

ID          NAME        AGE         ADDRESS     SALARY
----------  ----------  ----------  ----------  ----------
1           Paul        32          California  20000.0
2           Allen       25          Texas       15000.0
3           Teddy       23          Norway      20000.0
4           Mark        25          Rich-Mond   65000.0
5           David       27          Texas       85000.0
6           Kim         22          South-Hall  45000.0
7           James       24          Houston     10000.0
8           Paul        24          Houston     20000.0
9           James       44          Norway      5000.0
10          James       45          Texas       5000.0
SELECT name FROM COMPANY;
NAME
----------
Paul
Allen
Teddy
Mark
David
Kim
James
Paul
James
James
 SELECT DISTINCT name FROM COMPANY;
NAME
----------
Paul
Allen
Teddy
Mark
David
Kim
James

4.sqlite参考资料

1.sqlite在线编辑器:  SQL Online Compiler - Next gen SQL Editor

2.SQLite 教程 | 菜鸟教程

3.w3cschool

4.​​​​​​SQLite数据类型详解 - 虚-染D - 博客园

5.Qt帮助文档 

5.QT操作sqlite

1.概述

        本文假设您至少具有SQL的基本知识。您应该能够理解简单的SELECT、INSERT、UPDATE和DELETE语句。尽管QSqlTableModel类提供了一个不需要SQL知识的数据库浏览和编辑接口,但强烈建议对SQL有基本的了解。关于SQL数据库的标准文本是C. J. Date的《数据库系统简介》(第7版),ISBN 0201385902。

2.Qt数据库有关的类

        这些类提供对SQL数据库的访问。

QSqlDatabase 处理到数据库的连接                                                
QSqlDriverCreator 为特定驱动程序类型提供SQL驱动程序工厂的模板类        
QSqlDriverCreatorBase SQL驱动程序工厂的基类
QSqlDriver 用于访问特定SQL数据库的抽象基类
QSqlError SQL数据库错误信息                
QSqlField 操作SQL数据库表和视图中的字段
QSqlIndex 函数来操作和描述数据库索引
QSqlQuery 执行和操作SQL语句的方法                
QSqlRecord 封装数据库记录                                
QSqlResult 抽象接口访问特定SQL数据库的数据
QSql 包含Qt SQL模块中使用的各种标识符
QSqlQueryModel SQL结果集的只读数据模型        
QSqlRelationalTableModel 单个数据库表的可编辑数据模型,具有外键支持
QSqlTableModel 单个数据库表的可编辑数据模型

3.数据库类的分层

        SQL类分为三层:

        驱动层:

        其中包括QSqlDriver、QSqlDriverCreator、qsqldrivercreatebase、QSqlDriverPlugin和QSqlResult类。这一层提供了特定数据库和SQL API层之间的底层桥梁。有关更多信息,请参见SQL数据库驱动程序。

        SQL API层:

        这些类提供对数据库的访问。使用QSqlDatabase类进行连接。数据库交互是通过使用QSqlQuery类实现的。除了QSqlDatabase和QSqlQuery, SQL API层还支持QSqlError、QSqlField、QSqlIndex和QSqlRecord。

        用户接口层:

        These classes link data from the database to data-aware widgets. They include QSqlQueryModel, qsqlltablemodel and QSqlRelationalTableModel. These classes are designed for use with Qt's model/view framework.

Note: A QCoreApplication object must be instantiated before using any of these classes.

4. Use of database classes

        Qt uses the QSqlDatabase class to connect and open the database. The basic usage process is:

  1. Select database driver
  2. Set database name, address, ip, host name, username, password
  3. Open database
  4. Use QSqlQuery or QSqlQueryModel to execute database statements
  5. QSqlQuery uses QSqlRecord to view each record, and QSqlQueryModel can use QTableView to view it.

code segment:

 qDebug()<<QSqlDatabase::drivers();//打印所有数据库驱动
/*QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName = QLatin1String( defaultConnection ))
使用驱动程序类型和连接名称connectionName将数据库添加到数据库连接列表中。如果已经存在名为connectionName的数据库连接,则删除该连接。*/
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");//连接到数据库
/*void QSqlDatabase::setDatabaseName(const QString &name)
将连接的数据库名称设置为name。要生效,必须在打开连接之前设置数据库名称。或者,您可以close()连接,设置数据库名称,然后再次调用open()。*/
    db.setDatabaseName("test.db");//设定数据库名字
/*使用当前连接值打开数据库连接。成功时返回true;否则返回false。可以使用lastError()检索错误信息。*/
    bool f = db.open();
    if(!f){
        QSqlError err = db.lastError();//打印数据库错误
        qDebug()<< err.text();
    }
    QSqlQuery query(db);//定义QSqlQuery 使用QSqlQuery 执行sql语句
    f = query.exec("create table student(id int,name text,year int,addr text,learn int)");
    if(!f){
        QSqlError err = query.lastError();
        qDebug()<< err.text();
    }
    for(int i=0;i<1000000;i++){//插入1000000条数据
        f = query.exec(QString("insert into student values(%1,'ak%2',%3,'四川%4',%5)").arg(i).arg(i).arg(i/2+6).arg(i).arg(qrand()%100));
        if(!f){
            QSqlError err = query.lastError();
            qDebug()<< err.text()<<i;
        }
    }
    f = query.exec("select * from student");//查询student表格数据
    if(!f){
        QSqlError err = query.lastError();
        qDebug()<< err.text();
    }
    do {//打印每一列数据 query.count()可以返回列宽度
        QSqlRecord record = query.record();
        qDebug()<<record.count();
        qDebug()<<record.value(0).toInt();
        qDebug()<<record.value(1).toString();
        qDebug()<<record.value(2).toInt();
        qDebug()<<record.value(3).toString();
        qDebug()<<record.value(4).toInt();

    } while (query.next());
    //使用模型视图查看表格数据
    QSqlQueryModel *model = new QSqlQueryModel;
//    model->setTable("student");
    model->setQuery(QString("select * from student order by learn"),db);
    ui->tableView->setModel(model);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableView->installEventFilter(this);

Guess you like

Origin blog.csdn.net/klp1358484518/article/details/127387377