Embedded database sqlite3 basic command operation basis (05)

Preface

Data is widely used in practical work, and there are many database products, such as oracle, DB2, SQL2000, and mySQL; databases based on embedded Linux mainly include SQLite, Firebird, Berkeley DB, and eXtremeDB.

This article mainly explains the database SQLite. Through this small open source embedded database, we will guide you to master some basic database operations. These operations are common in many systems. It can be said that you can learn everything.

SQLite

picture

SQLite is a lightweight database and ACID-compliant relational database management system that is contained in a relatively small C library.

AuthorD.RichardHipp

In January 2000, Hipp began discussing with a colleague the idea of ​​creating a simple embedded SQL database that would use the GNU DBM hash library (gdbm) as a backend and would require no installation or administrative support. Later, whenever he had free time, Hipp began to implement this work. In August 2000, SQLite version 1.0 was released.

[Here I offer my knees to God!

Its design target is embedded, and it has been used in many embedded products. It takes up very low resources. In embedded devices, only a few hundred K of memory may be enough. It can support mainstream operating systems such as Windows/Linux/Unix, and can be combined with many programming languages, such as Tcl, C#, PHP, Java, etc., as well as the ODBC interface. It is also compared to the two open source programs Mysql and PostgreSQL. For the world's famous database management systems, its processing speed is faster than them all.

SQLite characteristics

  1. Zero configuration - no need to install and manage configuration;

  2. A complete database stored in a single disk file;

  3. Database files can be freely shared between machines with different byte order;

  4. Support database size up to 2TB;

  5. Small enough, the entire source code is approximately 30,000 lines of C code, 250KB;

  6. It operates on data faster than most popular databases today.

Install

The main version running now is sqlite3, and it is very convenient to install it under ubuntu.

sudo apt-get install sqlite sqlite3   安装应用程序
sudo apt-get install libsqlite3-dev   安装库+头文件,用代码操作数据库必须安装

View the version number: Enter the command sqlite3 to enter the operation interface, enter the command .version to view the detailed version number.

picture

You can also use the following command to install the graphical operation tool:

sudo apt-get install sqlitebrowser    图形化工具建立数据库

In addition, it can also be deployed under windows. This article only discusses the command line method to operate the database under ubtuntu.

type of data

Operating the database mainly involves operating tables. Each column of the table has a certain data type, such as integer values, strings, Boolean, etc.

The main data types of Sqlite3 are as follows:

type of data definition
Data type NULL Indicates that the value is NULL.
INTEGER Unsigned integer value.
REAL Floating point value.
TEXT Text strings, the encoding methods used for storage are UTF-8, UTF-16BE, and UTF-16LE.
BLOB Stores Blob data. This type of data is exactly the same as the input data. 1 means true and 0 means false.

At the same time, sqlite3 also accepts the following data types:

type of data definition
smallint 16-bit integer.
interger 32-bit integer.
decimal(p,s) The exact value p refers to how many decimal digits there are in total, and s refers to how many decimals there can be after the decimal point. If not specified, the system will default to p=5 s=0.
float 32-bit real number.
double 64-bit real number.
char(n) n length string, n cannot exceed 254.
varchar(n) A string whose length is not fixed and whose maximum length is n. n cannot exceed 4000.
graphic(n) Same as char(n), but its unit is two bytes, n cannot exceed 127. This form is to support two-byte length fonts, such as Chinese characters.
vargraphic(n) A two-character string of variable length with a maximum length of n, n cannot exceed 2000
date Contains year, month, date.
time Contains hours, minutes, and seconds.
timestamp Contains year, month, day, hour, minute, second, thousandth of a second.

constraint

Each column of the table has some restrictive attributes. For example, the data of some columns cannot be repeated, and some limit the data range. Constraints are used to further describe the data attributes of each column. Common constraints in SQLite databases are as follows:

name definition
NOT NULL - non empty
UNIQUE only
PRIMARY KEY primary key
FOREIGN KEY foreign key
CHECK condition check
DEFAULT default

NOT NULL

There are some fields that we may not know what to fill in at the moment, and there is no default value set for them. When adding data, we leave such fields blank, and the system considers them to be NULL values. But there is another type of field that must be filled in with data. If not filled in, the system will report an error. Such fields are called NOT NULL fields and need to be declared in advance when defining the table.

UNIQUE

In addition to the main column, there are also some columns that cannot have duplicate values.

PRIMARY KEY

Generally it is an integer or a string, as long as it is unique. In SQLite, if the primary key is an integer type, the value of the column can automatically grow.

FOREIGN KEY

There is already a Teachers table in our database. If we create another Students table, each student in the Students table must correspond to a teacher in the Teachers table. It's very simple. You only need to create a TeacherId field in the Students table and save the corresponding teacher's Id number. In this way, a relationship is established between students and teachers. The problem is: we may store a TeacherId value for students that is not in the Teachers table, and the error will not be found. In this case, you can declare the TeacherId field in the Students table as a foreign key so that its value corresponds to the Id field in the Teachers table. In this way, once a non-existent teacher ID is stored in the Students table, the system will report an error.

Default valueDEFAULT

There are some special field columns whose values ​​are basically the same in every record. It is only changed to other values ​​in individual cases. We can set a default value for such a field column.

Condition check CHECK

Certain values ​​must meet certain conditions before they are allowed to be stored. This requires the use of this CHECK constraint.

Common commands

The following introduces the use of common commands in Shell mode.

Order Function
.help Displays a list of all commands available in shell mode
.database Displays database information; contains the location of the current database
.mode  column Causes the results of SQL statement processing to be displayed in a column-aligned manner
.mode    list column
.headers on/off Turn on the column title display switch so that the query results have column titles when displayed on the screen.
.tables List how many tables there are in the currently open database
.exit Exit the SQLite environment
.schema foods Display the SQL statement when the table foods was created
.schema Display the statements when all tables were created
.nullvalue STRING When querying, the specified string is used instead of the output NULL string. The default value is .nullvalue ''
.show Display some output-related settings defined in shell mode
.output file.csv Set the output file format to CSV and the file name is file.csv
.separator , Set the column data output by the select statement to be separated by ","
.output stdout Restore output content to the standard output device (screen)

[Note] SQLite commands all start with ., and there is no . in front of the operation statement.

Usage examples

The operation statements of the database are mainly adding, deleting, modifying and searching. Below we will use some examples to let you understand these basic operations of the database.

table type

Suppose we want to create a teaching management database jxgl.db, and the student table STUDENT should be stored in the database.

sno takes off ssex sage sdept
95001 yikou m 21 cs
95002 peng m 21 cs

According to our common sense, the data in each column has the following characteristics:

  • sno student ID: an integer value. Each student's ID is unique. Schools generally use student IDs to distinguish all students, and generally student IDs are increasing, so we set sno as the primary key;

  • sname name: generally a string, can be repeated, but cannot be empty;

  • ssex gender: string, can be empty;

  • sage age: integer value, assuming the age is greater than 14;

  • sdept major: string, can be empty, here we default to 'CS'.

Below we implement all operations of this database step by step.

Create teaching management "jxgl" database

To open and exit the database, use the following commands.

picture

Create table:

CREATE TABLE IF NOT EXISTS STUDENT(Sno integer primary key,   Sname text not null,   Ssex text,Sage integer check(Sage>14),Sdept text default 'CS');

The attributes of this table are the results of executing the table attributes in the previous section:

picture

View table:

picture

Seeing STUDENT indicates that the table has been created. 【Notice】

  1. The operation statement is not a command, so do not add . in front of it;

  2. The operation statement must be followed by; at the end, if it is missing, a semicolon must be added;

  3. Operation statements are very sensitive to the full-width and half-width of letters, and all symbols must use half-width.

Insert data

Inserting data is implemented using the insert into statement, as shown below:

INSERT INTO STUDENT VALUES('95001','李勇','M',20,'CS');
INSERT INTO STUDENT VALUES('95002','刘晨','F',19,'IS');
INSERT INTO STUDENT VALUES('95003','王敏','F',18,'MA');
INSERT INTO STUDENT VALUES('95004','张立','M',18,'IS');

The execution results are as follows:

picture

 

Inserted data only initializes part of the value

The column that is set to not null must be assigned a value, and the table name is not case-sensitive.

insert into student(sname,sage) values ('一口',19);

picture

 

View table

Use the SELECT statement to view the contents of the table:

SELECT * FROM STUDENT;

The * indicates viewing all data information.

picture

Have you seen that the result looks uncomfortable? Let’s adjust the display format:

sqlite> .headers on          显示列名
sqlite> .mode column         列对齐

picture

 

Delete a line of information

delete from student where sname='一口';

picture

As can be seen from the picture above, the record named "One Mouth" has been deleted.

Modify a certain content of a record

UPDATE student SET sage=29 WHERE sname='张立';

picture

 

Modify the data table structure.

To modify the table structure, you need to use the statement ALTER TABLE. Next, we add the "spwd" column to the STUDENT table, whose data type is TEXT, and use the SELECT command to view the contents of the table.

ALTER TABLE STUDENT ADD spwd TEXT default '123456';

picture

 

Modify table name

alter table student rename to stu;

picture

 

Delete the data table.

DROP TABLE STUDENT;

Delete column

SQLite3 does not implement the command to delete a column. To achieve this operation, you need to copy the table to a new table first, but only the required columns are integrated, and the columns to be deleted are not inherited. You can delete a column in the following ways:

sqlite> create table test as select sno, sname,ssex,sage,sdept  from stu;
sqlite> drop table stu;
sqlite> alter table test rename to stu;

picture

As can be seen from the above figure, the column spwd we just added has been deleted.

sqlite advanced

where child clause

What should I do if I don't want to view all the data, but want to view the information of a specific person? We have to use the where clause to achieve this. The where clause can be combined with operation statements to process additions, deletions, modifications, and searches, and is the most commonly used clause.

Find records by name:

Select * from student where sname='一口';

picture

Search records based on student number:

Select * from student where sno=95001;

picture

Find records based on both name and age:

select *from student where sname='一口' and sage=19;

picture

Display data from two columns

select sno,sname from student ; 

picture

 

Database backup and recovery

Now we assume that we want to back up the table foods as foodsdb.sql and use commands to restore the database. Just follow these steps.

sqlite>.dump       --把创建表及向表中插入记录的所有SQL语句显示在屏幕上
sqlite>.output  foodsdb.sql --指定dump命令输出到文件的文件名
sqlite>.dump        --输出创建并插入数据到基本表的SQL语句到output指定的文件
sqlite>.output stdout  --恢复输出内容到标准输出设备(屏幕)
sqlite>.dump           --此时输出的SQL语句转回到屏幕 
sqlite>Drop table foods; --删除foods表语句说明:

The above Drop is a SQL statement used to delete the specified table. Because it is a SQL statement, it ends with ";"

sqlite>.read foodsdb.sql    --执行foodsdb.sql中的包含的所有SQL语句,用来重建刚删除的4张表及相关数据
 

Okay, let’s follow Yiyijun’s step-by-step operation. Basically, you will have no problem with the addition, deletion, modification and query operations of sqlite3. There are also some other clauses and function usage in sqlite, which will be introduced in the next article.

Guess you like

Origin blog.csdn.net/weixin_41114301/article/details/133385480