Home Swift UNIX C Assembly Go Web MCU Research Non-Tech

SQLite command line usage

2022-02-13 | Research | #Words: 1425 | 中文原版

Recently, I plan to use the open source and free SQLite as a database to save money. And due to personal habits, I prefer the command line, so I record how to use SQLite in command line.

For installation, macOS comes with sqlite3, and Linux can use the software package (apt-get or yum) to download.

Brief introduction to SQLite interactive operations

Here are some small operations outside of the database.

For example in macOS, after opening “Terminal”, enter the following command to open a database (if there is not one, a new one will be created):

sqlite3 database_name.db

At this time, you will enter the sqlite operation interface, like:

$ sqlite3 test.sql
SQLite version 3.36.0 2021-06-18 18:58:49
Enter ".help" for usage hints.
sqlite> 

Use .help to view click operations, such as saving as a new file, modifying the display mode:

sqlite> .help
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output

If you want to exit SQLite, we can enter .exit or press Control + D to exit. Like:

sqlite> .exit

Notice: except for point operations, other commands must end with a semicolon (;), otherwise SQLite will think that the command has not ended, and the following situation will occur:

sqlite> CREATE TABLE tbl2 (
   ...> 

In this case, we can enter a semicolon to indicate the end of the command, or we can use this to enter a long command, such as the following:

sqlite> CREATE TABLE tbl2 (
   ...>   f1 varchar(30) primary key,
   ...>   f2 text,
   ...>   f3 real
   ...> );
sqlite>

Create a new table in the database

After basic operations, now we can start to understand the four major database skills: addition, deletion, modification and search.

But we have to create a new table. Here we create a new 2-column table. The first column is named one, the data type is varchar (a character type), and the maximum number of characters is 20; the second column is named two in smallint (an integer type), the command is as follows:

sqlite> create table tbl1(one varchar(10), two smallint);

The name of table is tbl1.

Add, delete, modify and check

Add” here is to insert a piece of data, the method is as follows:

sqlite> insert into tbl1 values('hello!',10);
sqlite> insert into tbl1 values('goodbye', 20);

Here we insert two rows of data. Then check the table (here shows the previous and modified content and style):

sqlite> select * from tbl1;
hello!|10
goodbye|20
sqlite> .mode column
sqlite> select * from tbl1;
one      two
-------  ---
hello!   10 
goodbye  20 

Delete” is to delete one or more rows of data that meets specified requirement. For example, use the following command to delete the row where is hello in the one column:

sqlite> delete from tbl1 
   ...> where one='hello'
   ...> ;
sqlite> select * from tbl1;
one      two
-------  ---
goodbye  20 

Then we insert several pieces of data as follows to demonstrate deleting multiple pieces of data:

one      two
-------  ---
goodbye  20 
a        20 
b        20 
c        10 
c        20 

Let’s try:

sqlite> delete from tbl1
   ...> where two=20;
sqlite> select * from tbl1;
one  two
---  ---
c    10 

You can see all rows where column two equal to 20 have been deleted. You may also see that the value in string format needs to be enclosed in single quotes, and the integer can be directly equal to it.

Change means updating the data, but this also reminds us to add a column with unique data, such as id. But I won’t add it here, because it is just a demo. We change c in the first column to abc. The command is as follows:

sqlite> update tbl1
   ...> set one='abc'	# target value
   ...> where two=10;	# Filters
sqlite> select * from tbl1;
one  two
---  ---
abc  10 

Check is to select data that meets some conditions and display.

For example, if we search for data with value of two less than 20 in the tbl1 table, use the following command:

sqlite> select *
   ...> from tbl1
   ...> where two<20
   ...> ;
one  two
---  ---
abc  10 

Okay, now we can start to use SQLite. I will slowly write some skills into a separate blog.

I hope these will help someone in need~