当前位置:网站首页>SQLite3 syntax (2)

SQLite3 syntax (2)

2022-06-09 02:11:00 A-L-Kun

SQLite3 ( Two )

8、 ... and 、 Database configuration

1、 grammar

SQLite Of PRAGMA A command is a special command , Can be used in SQLite Control various environmental variables and status flags in the environment . One PRAGMA The value can be read , It can also be set according to requirements .

PRAGMA pragma_name;  -- Inquire about pragma_name Value 
PRAGMA pragma_name = value;  -- Set the value 

2、 Common configuration

2.1 auto_vacuum

2.1.1 VACUUM

VACUUM The command copies the contents of the main database to a temporary database file , Then empty the primary database , And reload the original database file from the copy . This eliminates free pages , Arrange the data in the table as continuous , In addition, the database file structure will be cleaned up .

If there is no explicit integer primary key in the table (INTEGER PRIMARY KEY),VACUUM The command may change the rows of entries in the table ID(ROWID).VACUUM The command only applies to the primary database , Additional database files are not possible to use VACUUM command .

If there is an active transaction ,VACUUM The command will fail .VACUUM A command is any operation for an in memory database . because VACUUM Command to recreate the database file from scratch , therefore VACUUM It can also be used to modify many database specific configuration parameters

grammar :

sqlite3 database_name "VACUUM;" -- Reload the entire database 
VACUUM;
VACUUM table_name;  -- Reloading data on a specific table 
2.1.2 Automatically VACUUM
PRAGMA [database.]auto_vacuum;
PRAGMA [database.]auto_vacuum = mode;
Pragma value describe
0 or NONE Ban Auto-vacuum. This is the default mode , This means that the database file size will not shrink , Unless used manually VACUUM command .
1 or FULL Enable Auto-vacuum, It's fully automatic . In this mode , Allow database files to shrink as data is removed from the database .
2 or INCREMENTAL Enable Auto-vacuum, But it must be activated manually . In this mode , The reference data is maintained , Free pages are only placed in the free list . These pages can be used at any time incremental_vacuum pragma To cover .

2.2 cache_size

Gets or temporarily sets the maximum size of the page cache in memory

PRAGMA [database.]cache_size;
PRAGMA [database.]cache_size = pages;

pages: Indicates the number of pages in the cache . The default size of the built-in page cache is 2,000 page , The minimum size is 10 page

2.3 case_sensitive_like

Control the built-in LIKE Case sensitivity of expressions . By default , The Pragma by false, It means , Built in LIKE The operator ignores the case of letters . The grammar is as follows :

PRAGMA case_sensitive_like = [true|false];

2.4 count_changes

Gets or sets the return value of the data operation statement , Such as INSERT、UPDATE and DELETE

PRAGMA count_changes;
PRAGMA count_changes = [true|false];

By default , The Pragma by false, These statements do not return anything . If set to true, Each statement mentioned will return a single row, single column table , Consists of a single integer value , This integer represents the rows affected by the operation

2.5 database_list

Will be used to list all database connections

PRAGMA database_list;

Returns a single row, three column table , Whenever you open or attach a database , The serial number in the database will be given , Its name and related files

2.6 encoding

Controls how strings are encoded and stored in database files . The grammar is as follows :

PRAGMA encoding;
PRAGMA encoding = format;

The format value can be UTF-8、UTF-16le or UTF-16be One of

2.7 freelist_count

Returns an integer , Indicates the number of database pages currently marked as free and available

PRAGMA [database.]freelist_count;

2.8 journal_mode

Gets or sets the log mode that controls how log files are stored and processed

PRAGMA [database.]journal_mode;
PRAGMA [database.]journal_mode = mode;
Pragma value describe
DELETE The default mode . In this mode , At the end of the transaction , The log file will be deleted .
TRUNCATE The log file is phased to zero byte length .
PERSIST The log file is left in place , But the head is rewritten , Indicates that the log is no longer valid .
MEMORY Logging is kept in memory , Not on disk .
OFF Do not keep any log records .

2.9 max_page_count

Gets or sets the maximum number of pages allowed for the database

PRAGMA [database.]max_page_count;
PRAGMA [database.]max_page_count = max_page;

2.10 page_size

Gets or sets the size of the database page

PRAGMA [database.]page_size;
PRAGMA [database.]page_size = bytes;
-- After resizing , Use vacuum Refresh the page 
VACUUM;

2.11 parser_trace

As it parses SQL Command to control the debug status of printing , The default is flase,SQL The parser doesn't parse with it SQL Command to print out its status

PRAGMA parser_trace = [true|false];

2.12 secure_delete

PRAGMA [database.]secure_delete;
PRAGMA [database.]secure_delete = [true|false];

Controls how content is deleted from the database , The default value of the safe delete flag is usually off

2.13 temp_store

Gets or sets the storage mode used by the temporary database file

PRAGMA temp_store;
PRAGMA temp_store = mode;
Pragma value describe
0 or DEFAULT The default mode is compile time . Usually FILE.
1 or FILE Use file based storage .
2 or MEMORY Use memory based storage .

2.14 temp_store_directory

Gets or sets the location of the temporary database file

PRAGMA temp_store_directory;
PRAGMA temp_store_directory = 'directory_path';

2.15 writable_schema

Gets or sets whether system tables can be modified

PRAGMA writable_schema;
PRAGMA writable_schema = [true|false];

If this... Is set Pragma, Then table with sqlite_ Start , You can create and modify , Include sqlite_master surface . Use this Pragma Pay attention to , Because it may cause damage to the entire database

There are other configuration methods , You can go to Official documents Find out for yourself

Nine 、 sqlite constraint

Constraints are rules that are enforced on the data columns of a table . These are used to limit the types of data that can be inserted into the table . This ensures the accuracy and reliability of the data in the database

Constraints can be column level or table level . Column level constraints apply only to columns , Table level constraints are applied to the entire table

  • NOT NULL constraint : Make sure that a column cannot have NULL value
  • DEFAULT constraint : When a column has no specified value , Provide default values for this column
  • UNIQUE constraint : Make sure that all values in a column are different
  • PRIMARY Key constraint : Uniquely identifies the rows in the database table / Record
  • CHECK constraint :CHECK Constraints ensure that all values in a column meet certain conditions

1、NOT NULL constraint

By default , Columns can be saved NULL value . If you don't want a column to have NULL value , Then you need to define this constraint on this column , Specifies that... Is not allowed on this column NULL value

NULL It's different from having no data , It represents unknown data

for example :

CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,  -- Null values are not accepted 
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

2、DEFAULT constraint

DEFAULT Constrained by INSERT INTO Statement does not provide a specific value , Provide a default value for the column

for example :

CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL    DEFAULT 50000.00  -- If not set , The default value is 50000.00
);

3、UNIQUE constraint

UNIQUE Constraints prevent the existence of two records with the same value in a particular column . stay COMPANY In the table , for example , You may want to prevent two or more people of the same age .

CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL UNIQUE,  -- The name is unique 
   ADDRESS        CHAR(50),
   SALARY         REAL    DEFAULT 50000.00
);

4、PRIMARY KEY constraint

PRIMARY KEY The constraint uniquely identifies each record in the database table . There can be more than one in a table UNIQUE Column , But there can only be one primary key . When designing database tables , Primary keys are very important . The primary key is unique ID

We use primary keys to refer to rows in the table . You can set the primary key as the foreign key of other tables , To create relationships between tables . because " Coding supervision exists for a long time ", stay SQLite in , The primary key can be NULL, This is different from other databases

A primary key is a field in a table , Uniquely identifies the rows in the database table / Record . The primary key must contain a unique value . Primary key column cannot have NULL value

A table can only have one primary key , It can consist of one or more fields . When multiple fields are used as primary keys , They are called Composite key

If a table defines a primary key on any field , Then no two records on these fields can have the same value

CREATE TABLE COMPANY(
   ID INT PRIMARY KEY     NOT NULL,  -- bring id Primary key 
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL
);

5、CHECK constraint

CHECK Constraint enable enter a condition that records the value to be checked . If the condition value is false, The record violates the constraint , And cannot be entered into the table .

CREATE TABLE COMPANY3(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT    NOT NULL,
   AGE            INT     NOT NULL,
   ADDRESS        CHAR(50),
   SALARY         REAL    CHECK(SALARY > 0)
);

6、 AUTOINCREMENT constraint

AUTOINCREMENT Constraints should be used in combination with primary key constraints , meanwhile , It can only be used for integer fields

CREATE TABLE COMPANY(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
    name TEXT NOT NULL ,
    age INT CHECK ( age >= 18 and age <= 50 ),  -- Age limits 
    salary REAL DEFAULT 1000.0  -- The default value is 1000
);

Be careful : Use DELETE FROM table_name Method cannot zero an incrementor

DELETE FROM sqlite_sequence WHERE name = 'table_name';  -- Make the increment of the table return to zero 

SQLite When the database contains self incrementing Columns , Will automatically create a new one called sqlite_sequence Table of . This table contains two columns :name and seq.name Record the table where the self addition column is located ,seq Record the current serial number ( The number of the next record is the current serial number plus 1). If you want to reset the serial number of a self incremented column to zero , It just needs to be modified sqlite_sequence The watch will do

UPDATE sqlite_sequence SET seq = 0 WHERE name = 'table_name';

Ten 、 High order query

1、 Multi-table query

SQLite Of Join Clause is used to combine the records of tables in two or more databases .JOIN Is a means of combining fields in two tables by common values .

SQL Three main types of connections are defined :

  • Cross connect - CROSS JOIN
  • Internal connection - INNER JOIN
  • External connection - OUTER JOIN

1.1 Cross connect

Cross connect (CROSS JOIN) Match each row of the first table with each row of the second table . If the two input tables have x and y That's ok , Then the result table has x*y That's ok . Due to cross connection (CROSS JOIN) It is possible to produce very large tables , Use with caution , Use them only when appropriate

Cross connect operation , They all return the Cartesian product of all data rows of the two connected tables , The number of returned data rows is equal to the number of qualified data rows in the first table multiplied by the number of qualified data rows in the second table

SELECT EMP_ID, NAME, DEPT FROM COMPANY CROSS JOIN DEPARTMENT;  -- Select the... Of two tables id,name,dept

1.2 Internal connection

Internal connection (INNER JOIN) Combine two tables according to the join predicate (table1 and table2) To create a new result table . The query will table1 Every line in is related to table2 Compare each line in , Find matching pairs for all rows that satisfy the join predicate . When the join predicate is satisfied ,A and B The column values of each matching pair of rows are merged into a result row

Internal connection (INNER JOIN) Is the most common connection type , Is the default connection type .INNER Keywords are optional

Here is the inner connection (INNER JOIN) The grammar of :

SELECT ... FROM table1 [INNER] JOIN table2 ON conditional_expression ...

You can also use USING Expression declaration inner connection (INNER JOIN) Conditions . This expression specifies an or - A list of multiple columns :

SELECT ... FROM table1 JOIN table2 USING ( column1 ,... ) ... 

Natural join (NATURAL JOIN) Be similar to JOIN...USING, But it will automatically test the equality between the values of each column in the two tables :

SELECT ... FROM table1 NATURAL JOIN table2...

for example :

SELECT EMP_ID, NAME, DEPT FROM COMPANY INNER JOIN DEPARTMENT
        ON COMPANY.ID = DEPARTMENT.EMP_ID;  

1.3 External connection

External connection (OUTER JOIN) It's internal connection (INNER JOIN) An extension of . although SQL The standard defines three types of external connections :LEFTRIGHTFULL, but SQLite Only support The left outer join (LEFT OUTER JOIN

External connection (OUTER JOIN) Method of declaring condition and inner connection (INNER JOIN) It's the same , Use ONUSING or NATURAL Key words to express . The initial result table is calculated in the same way . Once the main connection calculation is completed , External connection (OUTER JOIN) Merge any unconnected rows from one or two tables , Outer joined columns use NULL value , Attach them to the results table .

Below is the left outer connection (LEFT OUTER JOIN) The grammar of :

SELECT ... FROM table1 LEFT OUTER JOIN table2 ON conditional_expression ...

You can also use USING Expression declaration outer connection (OUTER JOIN) Conditions . This expression specifies a list of one or more columns , Returns the result that the specified columns are equal :

SELECT ... FROM table1 LEFT OUTER JOIN table2 USING ( column1 ,... ) ...

Natural join (NATURAL JOIN) Be similar to JOIN...USING, But it will automatically test the equality between the values of each column in the two tables :

SELECT ... FROM table1 NATURAL LEFT OUTER JOIN table2...

2、 Unions Clause

SQLite Of UNION Clause / Operator is used to merge two or more SELECT Result of statement , Do not return any duplicate rows .

In order to use UNION, Every SELECT The number of columns selected must be the same , The same number of list expressions , Same data type , And make sure they are in the same order , But they don't have to be the same length

Combine two result sets , Do not include repeating lines , At the same time, sort the default rules

2.1 grammar

UNION The basic grammar is as follows :

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

UNION

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

2.2 UNION ALL

UNION ALL Operator is used to combine two SELECT Result of statement , Include repeating lines .

Combine two result sets , Include repeating lines , No sorting

Apply to UNION The same rules apply to UNION ALL Operator .

UNION ALL The basic grammar is as follows :

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

UNION ALL

SELECT column1 [, column2 ]
FROM table1 [, table2 ]
[WHERE condition]

3、 Query nesting

3.1 Subquery

Subqueries, or internal queries 、 nested queries , Refer to SQLite In the inquiry WHERE Clause to embed query statements .

One SELECT The query result of a statement can be used as the input value of another statement .

Subqueries can be associated with SELECTINSERTUPDATE and DELETE Statement together , It can be accompanied by the use of operators such as =、<、>、>=、<=、IN、BETWEEN etc. .

Here are some rules that subqueries must follow :

  • Subqueries must be enclosed in parentheses
  • Subquery in SELECT Clause can only have one column , Unless there are multiple columns in the main query , Compare with the selected column of the subquery
  • ORDER BY Cannot be used in subqueries , Although the main query can use ORDER BY. You can use... In subqueries GROUP BY, Function and ORDER BY identical
  • The subquery returns more than one row , Can only be used with multivalued operators , Such as IN Operator
  • BETWEEN Operator cannot be used with subquery , however ,BETWEEN Can be used within subqueries

3.2 grammar

SELECT

SELECT column_name [, column_name ]
FROM   table1 [, table2 ]
WHERE  column_name operator
      (SELECT column_name [, column_name ]
      FROM table1 [, table2 ]
      [WHERE])

INSERT

INSERT INTO table_name [ (column1 [, column2 ]) ]
           SELECT [ *|column1 [, column2 ]
           FROM table1 [, table2 ]
           [ WHERE VALUE OPERATOR ]

UPDATA

UPDATE table
SET column_name = new_value
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME)
   [ WHERE) ]

DELETE

DELETE FROM TABLE_NAME
[ WHERE OPERATOR [ VALUE ]
   (SELECT COLUMN_NAME
   FROM TABLE_NAME
   [ WHERE ])]

``

11、 ... and 、 Null values and aliases

1、 Null value

SQLite Of NULL Is used to represent an item with a missing value . One of the tables NULL A value is a value that appears blank in the field

with NULL A field with a value is a field without a value .NULL Values are different from zero values or fields containing spaces , It is very important to understand this

CREATE TABLE users1(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,  -- Self increasing constraint , Non empty constraint , Primary key constraint 
    name TEXT ,
    pwd TEXT NOT NULL
);
INSERT INTO users1 (name, pwd) VALUES (NULL, '123');
INSERT INTO users1 (name, pwd) VALUES ('kun', '123234');
SELECT * FROM users1 WHERE (name IS NOT NULL);  -- If the primary key is not empty 

2、 Alias

Temporarily rename the table or column to another name , This is known as Alias . Using a table alias refers to a specific SQLite Rename table in statement . Renaming is a temporary change , The name of the actual table in the database does not change

Column names are used for a specific SQLite Statement renames a column in a table

SELECT column1, column2....
FROM table_name AS alias_name  -- Aliasing tables 
WHERE [condition];

SELECT column_name AS alias_name  -- Alias the column 
FROM table_name
WHERE [condition];

example :

SELECT * FROM users AS U
WHERE U.name == 'kun';

Twelve 、 trigger

1、 brief introduction

SQLite ** trigger (Trigger)** Is the callback function of the database , It will automatically execute when the specified database event occurs / call . The following is about SQLite The trigger of (Trigger) Main points :

  • SQLite The trigger of (Trigger) You can specify that it occurs in a specific database table DELETE、INSERT or UPDATE Trigger when , Or trigger when one or more columns of the specified table are updated .
  • SQLite Only support FOR EACH ROW trigger (Trigger), No, FOR EACH STATEMENT trigger (Trigger). therefore , Specify clearly FOR EACH ROW It's optional .
  • WHEN Clauses and triggers (Trigger) Actions may access and use forms NEW.column-name and OLD.column-name Insert reference to 、 Delete or update line elements , among column-name Is the name of the column from the table associated with the trigger .
  • Provided WHEN Clause , Only for WHEN Clause specifies line execution for true SQL sentence . If not provided WHEN Clause , For all lines SQL sentence .
  • BEFORE or AFTER The keyword determines when the trigger action is executed , The decision is to insert 、 Perform trigger actions before or after modification or deletion .
  • When the table associated with the trigger is deleted , Auto delete trigger (Trigger).
  • The table to be modified must exist in the same database , Tables or views attached as triggers , And only tablename, instead of database.tablename.
  • A special SQL function RAISE() It can be used to throw an exception in the trigger program .

2、 grammar

CREATE  TRIGGER trigger_name [BEFORE|AFTER] event_name 
ON table_name
BEGIN
 --  Trigger logic ....
END;

event_name:INSERT、DELETE、UPDATE

for example :

-- Main table 
CREATE TABLE COMPANY(
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
    name TEXT NOT NULL ,
    age INT CHECK ( age >= 18 and age <= 50 ),  -- Age limits 
    salary REAL DEFAULT 1000.0  -- The default value is 1000
);
-- A table for logging 
CREATE TABLE log_company(
    id INTEGER NOT NULL ,  -- Of a table that records changes id
    time TEXT NOT NULL -- Record the time when the table was modified 
);
-- Create trigger 
CREATE TRIGGER log_company_t AFTER INSERT ON COMPANY  -- Triggered when inserting table data 
BEGIN
   INSERT INTO log_company VALUES (new.id, DATETIME(CURRENT_TIMESTAMP,'localtime'));  --new Represents the inserted data 
END;
-- Insert data into table 
INSERT INTO COMPANY (id, name, age) VALUES (1, 'LIHUA', 19);
-- Set the output mode , View the data in the log record 
.mode column
SELECT * FROM log_company;

3、 Trigger other operations

see

SELECT name FROM sqlite_master
WHERE type = 'trigger';  -- from  sqlite_master  All triggers are listed in the table 

Delete

DROP TRIGGER trigger_name;

13、 ... and 、 Indexes

1、 brief introduction

Indexes (Index) Is a special look-up table , Database search engines are used to speed up data retrieval . In short , An index is a pointer to data in a table . The index in a database is very similar to the index directory of a Book

Take the catalog page of the Chinese Dictionary ( Indexes ) Let's say , We can press Pinyin 、 stroke 、 A catalogue sorted by radicals, etc ( Indexes ) Quickly find the words you need

Indexing helps speed up SELECT Query and WHERE Clause , But it slows down use UPDATE and INSERT Statement . Indexes can be created or deleted , But it doesn't affect the data

Use CREATE INDEX Statement to create an index , It allows named indexes , Specify the table and one or more columns to index , And indicates whether the index is in ascending or descending order

Indexes can also be unique , And UNIQUE Constraint similar , Prevent duplicate entries on columns or column combinations

Although the purpose of index is to improve the performance of database , But there are several situations where you need to avoid using indexes . When using indexes , The following guidelines should be reconsidered :

  • Indexes should not be used on smaller tables
  • Indexes should not be used on tables with frequent mass updates or inserts
  • An index should not be used when it contains a large number of NULL On the value column
  • Indexes should not be used on frequently operated Columns

Create method :

CREATE INDEX index_name ON table_name;

2、 establish

2.1 Single index

A single column index is an index created on only one column of a table

CREATE INDEX index_name
ON table_name (column_name);

2.2 unique index

Using unique indexes is not just for performance , But also for data integrity . The unique index does not allow any duplicate values to be inserted into the table

CREATE UNIQUE INDEX index_name
on table_name (column_name);

2.3 Composite index

A composite index is an index created on two or more columns of a table

CREATE INDEX index_name
on table_name (column1, column2);

Implicit indexing is when creating objects , An index automatically created by a database server . Indexes are automatically created as primary key constraints and unique constraints

3、 Look at the index

 .indices table_name
 OR
 SELECT * FROM sqlite_master WHERE type = 'index';

4、 Delete index

DROP INDEX index_name;

5、 Use index

"INDEXED BY index-name" Clause specifies that a named index must be used to find the values in the previous table

SELECT|DELETE|UPDATE column1, column2... 
FROM table_name
INDEXED BY (index_name)
WHERE (CONDITION);

fourteen 、 View

1、 brief introduction

View (View) It's just one that's stored in the database by the relevant name SQLite sentence . View (View) It's actually a predefined SQLite Combination of tables in the form of query .

View (View) You can include all rows of a table or select rows from one or more tables . View (View) You can create... From one or more tables , It depends on which view you want to create SQLite Inquire about .、

View (View) It's a kind of virtual table , Allow users to implement the following :

  • The way users or user groups find structured data is more natural or intuitive .
  • Restrict data access , Users can only see limited data , Instead of a complete table .
  • Summarize the data in various tables , Used to generate reports .

SQLite The view is read-only , Therefore, it may not be possible to execute... On the view DELETEINSERT or UPDATE sentence . But you can create a trigger on the view , When trying DELETEINSERT or UPDATE View , The actions that need to be done are defined in the trigger content

2、 establish

SQLite The view is to use CREATE VIEW Statement created by .SQLite Views can be from a single table 、 Create multiple tables or other views

CREATE [TEMP | TEMPORARY] VIEW view_name AS
SELECT column1, column2.....
FROM table_name
WHERE [condition];

Can be in SELECT Statement contains multiple tables , This is different from in normal SQL SELECT The way in the query is very similar . If an optional... Is used TEMP or TEMPORARY keyword , The view will be created in the temporary database

3、 Delete

To delete a view , Just use the with view_name Of DROP VIEW sentence

DROP VIEW view_name;

15、 ... and 、 Business

1、 brief introduction

A transaction is a unit of work that performs on a database . A transaction is a work unit or sequence completed in logical order , It can be done manually by the user , It can also be automatically completed by some database program

A transaction is an extension of one or more change databases . for example , If you are creating a record or updating a record or deleting a record from the table , Then you are executing transactions on this table . It is important to control transactions to ensure data integrity and handle database errors

actually , You can put a lot of SQLite Combine queries into a group , Put all this together and execute it as part of the transaction

Transaction properties ( ACID):

  • Atomicity : Ensure that all operations within the work unit are completed successfully , otherwise , The transaction terminates in the event of a failure , The previous operation will also be rolled back to the previous state .
  • Uniformity : Ensure that the database changes state correctly on successfully committed transactions .
  • Isolation, : Make transaction operations independent and transparent .
  • persistence : Ensure that the results or effects of committed transactions still exist in the event of system failure .

2、 grammar

2.1 Open transaction

Transactions can use BEGIN TRANSACTION Command or simple BEGIN Command to start . This type of transaction usually continues , Until we meet the next one COMMIT or ROLLBACK command . But when the database is shut down or an error occurs , Transactions also roll back .

BEGIN;
or 
BEGIN TRANSACTION;

2.2 Commit transaction

COMMIT Command is a transaction command used to save the changes invoked by a transaction to the database .

COMMIT The command has been changed since last COMMIT or ROLLBACK All transactions since the command are saved to the database .

COMMIT;
or
END TRANSACTION;

2.3 Cancellation of transaction

ROLLBACK Command is a transaction command used to undo transactions that have not been saved to the database

ROLLBACK The command can only be used to undo since the last time COMMIT or ROLLBACK Transaction command since command

ROLLBACK;

sixteen 、 Common functions

1、 Time date

function example
date(timestring, modifier, modifier, ...) With YYYY-MM-DD Format return date
time(timestring, modifier, modifier, ...) With HH:MM:SS Format return time
datetime(timestring, modifier, modifier, ...) With YYYY-MM-DD HH:MM:SS Format return
julianday(timestring, modifier, modifier, ...) This will return to BC from Greenwich mean time 4714 year 11 month 24 The number of days from noon on the day
strftime(format, timestring, modifier, modifier, ...) This will return the formatted date... Based on the format string specified by the first parameter
Time string example
YYYY-MM-DD2022-06-06
YYYY-MM-DD HH:MM2022-06-06 12:10
YYYY-MM-DD HH:MM:SS.SSS2022-06-06 12:10:04.100
MM-DD-YYYY HH:MM06-06-2022 12:10
HH:MM12:10
YYYY-MM-DDTHH:MM2022-06-06 12:10
HH:MM:SS12:10:01
YYYYMMDD HHMMSS20220606 121001
now2022-06-06

More can be found in :【https://www.runoob.com/sqlite/sqlite-date-time.html】 Study

2、 Other functions

2.1 grammar

function describe
COUNT Used to calculate the number of rows in a database table
MAX Allows us to select the maximum value of a column
MIN Allows us to select the minimum value of a column
AVG Calculate the average of a column
SUM Allow summation for a numeric column
RANDOM Between a return ±9223372036854775808 and Between pseudo-random integers
ABS Returns the absolute value of a numeric parameter
UPPER Convert strings to uppercase letters
LOWER Convert strings to lowercase letters
LENGTH Returns the length of the string
sqlite_version return SQLite Version of the library

2.2 Examples of use

BEGIN ;-- Start business 
SELECT UPPER('Hello'); -- All uppercase letters 
SELECT SQLITE_VERSION();  -- Returns the version of the database 
SELECT LENGTH('HELLO');  -- Returns the length of the string 
SELECT DATETIME(CURRENT_TIMESTAMP, 'NOW');  -- Gets the current time , Also use the current time zone 
COMMIT ;
原网站

版权声明
本文为[A-L-Kun]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/159/202206081407191654.html