当前位置:网站首页>SQLite3 syntax (2)
SQLite3 syntax (2)
2022-06-09 02:11:00 【A-L-Kun】
List of articles
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_nameMethod cannot zero an incrementorDELETE FROM sqlite_sequence WHERE name = 'table_name'; -- Make the increment of the table return to zero
SQLiteWhen the database contains self incrementing Columns , Will automatically create a new one calledsqlite_sequenceTable of . This table contains two columns:nameandseq.nameRecord the table where the self addition column is located ,seqRecord 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 modifiedsqlite_sequence The watch will doUPDATE 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 :LEFT、RIGHT、FULL, 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 ON、USING 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 SELECT、INSERT、UPDATE 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
SELECTClause can only have one column , Unless there are multiple columns in the main query , Compare with the selected column of the subquery ORDER BYCannot be used in subqueries , Although the main query can useORDER BY. You can use... In subqueriesGROUP BY, Function andORDER BYidentical- The subquery returns more than one row , Can only be used with multivalued operators , Such as
INOperator BETWEENOperator cannot be used with subquery , however ,BETWEENCan 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 :
SQLiteThe 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 .SQLiteOnly supportFOR EACH ROWtrigger (Trigger), No,FOR EACH STATEMENTtrigger (Trigger). therefore , Specify clearlyFOR EACH ROWIt's optional .WHENClauses and triggers (Trigger) Actions may access and use formsNEW.column-nameandOLD.column-nameInsert reference to 、 Delete or update line elements , amongcolumn-nameIs the name of the column from the table associated with the trigger .- Provided
WHENClause , Only forWHENClause specifies line execution for trueSQLsentence . If not providedWHENClause , For all linesSQLsentence . BEFOREorAFTERThe 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 ofdatabase.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 DELETE、INSERT or UPDATE sentence . But you can create a trigger on the view , When trying DELETE、INSERT 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-DD | 2022-06-06 |
YYYY-MM-DD HH:MM | 2022-06-06 12:10 |
YYYY-MM-DD HH:MM:SS.SSS | 2022-06-06 12:10:04.100 |
MM-DD-YYYY HH:MM | 06-06-2022 12:10 |
HH:MM | 12:10 |
YYYY-MM-DDTHH:MM | 2022-06-06 12:10 |
HH:MM:SS | 12:10:01 |
YYYYMMDD HHMMSS | 20220606 121001 |
now | 2022-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 ;
边栏推荐
- 大四学长谈程序员
- C语言仓库货物管理系统
- Kubernetes scheduling framework extension point
- 【Unity在Inspector面板修改值时销毁物体或组件】
- Shell trimloader
- file_ get_ contonts[ZJCTF 2019]NiZhuanSiWei
- 关于#数据库#的问题:请问vba+sql用select * from A where name1 regexp '护',错误提示“操作符丢失”
- Codeforces Round #797 (Div. 3)A~E
- C语言疫苗预约管理系统
- Read the log + regularize and extract the desired content + write the script to csv/xlsx
猜你喜欢

Servlet

Integrated base process test summary

Shell loop for while (IV)

Explain sentinel fusing strategy, degradation rules and flow control

20、ADS使用记录之E类功放设计(上)

Kubernetes scheduling framework extension point

年轻人“新宠”冷泡茶:能否开启下一个“立顿时代”?

How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)

Classify the audio and put it into the corresponding folder according to the file name

Jedis工具类、适配单个redis以及redis集群
随机推荐
[SUCTF 2019]EasyWeb
C语言猜数字游戏
Mp4 structure
C语言校园超市管理系统
Shell reports server information
How Bi makes SaaS products have a "sense of security" and "sensitivity" (Part I)
C language library management system
Redis集群搭建
A practical comprehensive navigation website
SEC asset management - swebui open source application solution
《C 语言程序设计实践》任务书
Classify the audio and put it into the corresponding folder according to the file name
Indonesia widya robotics and Huawei cloud make the safety of construction sites visible
Thread synchronization, process synchronization, mutex, semaphore, condition variable, etc
GCD Locks Dead cycle SpinLock synchronized
PHP replicated vulnerability
Phar deserialization learning swpuctf2018 simplephp
Former Disney executive says Depp will return to pirates of the Caribbean to continue playing Captain
String 3-387. First unique character in string
C language student native place information record book