Sqlite3 command line usage

Source: Internet
Author: User

// Content from www.sqlite.org/sqlite.html

Sqlite3: a command-line access program for SQLite Databases

The SQLite library has des a simple command-line utility namedSqlite3That allows the user to manually enter and execute SQL commands against an SQLite database. This document provides a brief introduction on how to useSqlite3.

Getting started

To startSqlite3Program, just type "sqlite3" followed by the name the file that holds the SQLite database. If the file does not exist, a new one is created automatically.Sqlite3Program will then prompt you to enter SQL. Type in SQL statements (terminated by a semicolon), press "enter" and the SQL will be executed.

For example, to create a new SQLite database named "ex1" with a single table named "tbl1", you might do this:

$Sqlite3 ex1
SQLite version 3.3.10
Enter ". Help" for instructions
SQLite>Create Table tbl1 (one varchar (10), two smallint );
SQLite>Insert into tbl1 values ('Hello! ', 10 );
SQLite>Insert into tbl1 values ('Goodbye ', 20 );
SQLite>Select * From tbl1;
Hello! | 10
Goodbye | 20
SQLite>

You can terminate the sqlite3 program by typing your systems end-of-file character (usually a control-d) or the interrupt character (usually a control-C ).

Make sure you type a semicolon at the end of each SQL command! The sqlite3 program looks for a semicolon to know when your SQL command is complete. if you omit the semicolon, sqlite3 will give you a continuation prompt and wait for you to enter more text to be added to the current SQL command. this feature allows you to enter SQL commands that span multiple lines. for example:

SQLite>Create Table tbl2 (
...>F1 varchar (30) primary key,
...>F2 text,
...>F3 real
...>);
SQLite>

ASIDE: querying the sqlite_master table

The database schema in an SQLite database is stored in a special table named "sqlite_master ". you can execute "select" statements against the special sqlite_master table just like any other table in an SQLite database. for example:

$Sqlite3 ex1
SQLite vresion 3.3.10
Enter ". Help" for instructions
SQLite>Select * From sqlite_master;
Type = table
Name = tbl1
Tbl_name = tbl1
Rootpage = 3
SQL = CREATE TABLE tbl1 (one varchar (10), two smallint)
SQLite>

But you cannot execute drop table, update, insert or delete against the sqlite_master table. the sqlite_master table is updated automatically as you create or drop tables and indices from the database. you can not make manual changes to the sqlite_master table.

The schema for temporary tables is not stored in the "sqlite_master" table since temporary tables are not visible to applications other than the application that created the table. the schema for temporary tables is stored in another special table named "sqlite_temp_master ". the "sqlite_temp_master" table is temporary itself.

Special commands to sqlite3

Most of the time, sqlite3 just reads lines of input and passes them on to the SQLite library for execution. but if an input line begins with a dot (". "), then that line is intercepted and interpreted by the sqlite3 program itself. these "dot commands" are typically used to change the output format of queries, or to execute certain prepackaged query statements.

For a listing of the available dot commands, you can enter ". Help" at any time. For example:

SQLite>. Help
. Bail On | off stop after hitting an error. Default off
. Databases list names and files of attached Databases
. Dump? Table? ... Dump the database in an SQL text format
. Echo on | off turn command echo on or off
. Exit exit this program
. Explain on | off turn output mode suitable for explain on or off.
. Header (s) on | off turn display of headers on or off
. Help show this message
. Import file table import data from file into table
. Indices table show names of all indices on table
. Load file? Entry? Load an extension Library
. Mode mode? Table? Set output mode where mode is one:
CSV comma-separated values
Column left-aligned columns. (See. width)
HTML <Table> code
Insert SQL insert statements for table
Line one value per line
List values delimited by. Separator string
Tabs tab-separated values
TCL list elements
. Nullvalue string print string in place of null values
. Output Filename send output to filename
. Output stdout send output to the screen
. Prompt main continue Replace the standard prompts
. Quit exit this program
. Read filename Execute SQL in Filename
. Schema? Table? Show the create statements
. Separator string change Separator Used by output mode and. Import
. Show show the current values for various settings
. Tables? Pattern? List names of tables matching a like pattern
. Timeout MS try opening locked tables for MS milliseconds
. Width num... Set column widths for "column" Mode
SQLite>

Changing output formats

The sqlite3 program is able to show the results of a query in eight different formats: "CSV", "column", "html", "insert", "line ", "tabs", and "TCL ". you can use ". mode "dot command to switch between these output formats.

The default output mode is "list ". in list mode, each record of a query result is written on one line of output and each column within that record is separated by a specific separator string. the default separator is a pipe symbol ("| "). list mode is especially useful when you are going to send the output of a query to another program (such as awk) for additional processing.

SQLite>. Mode list
SQLite>Select * From tbl1;
Hello | 10
Goodbye | 20
SQLite>

You can use the ". separator" dot command to change the separator for list mode. For example, to change the separator to a comma and a space, you cocould do this:

SQLite>. Separator ","
SQLite>Select * From tbl1;
Hello, 10
Goodbye, 20
SQLite>

In "line" mode, each column in a row of the database is shown on a line by itself. each line consists of the column name, an equal sign and the column data. successive records are separated by a blank line. here is an example of line mode output:

SQLite>. Mode line
SQLite>Select * From tbl1;
One = Hello
Two = 10
One = goodbye
Two = 20
SQLite>

In column mode, each record is shown on a separate line with the data aligned in columns. For example:

SQLite>. Mode Column
SQLite>Select * From tbl1;
One Two
--------------------
Hello 10
Goodbye 20
SQLite>

By default, each column is at least 10 characters wide. data that is too wide to fit in a column is truncated. you can adjust the column widths using ". width "command. like this:

SQLite>. Width 12 6
SQLite>Select * From tbl1;
One Two
------------------
Hello 10
Goodbye 20
SQLite>

The ". width "command in the example above sets the width of the first column to 12 and the width of the second column to 6. all other column widths were unaltered. you can gives as your arguments ". width "as necessary to specify the widths of as specified columns as are in your query results.

If you specify a column a width of 0, then the column width is automatically adjusted to be the maximum of three numbers: 10, the width of the header, and the width of the first row of data. this makes the column width self-adjusting. the default width setting for every column is this auto-adjusting 0 value.

The column labels that appear on the first two lines of output can be turned on and off using ". header "dot command. in the examples abve, the column labels are on. to turn them off you cocould do this:

SQLite>. Header off
SQLite>Select * From tbl1;
Hello 10
Goodbye 20
SQLite>

Another useful output mode is "insert ". in insert mode, the output is formatted to look like SQL insert statements. you can use insert mode to generate text that can later be used to input data into a different database.

When specifying insert mode, you have to give an extra argument which is the name of the table to be inserted into. For example:

SQLite>. Mode insert new_table
SQLite>Select * From tbl1;
Insert into 'new _ table' values ('hello', 10 );
Insert into 'new _ table' values ('Goodbye ', 20 );
SQLite>

The last output mode is "html ". in this mode, sqlite3 writes the results of the query as An XHTML table. the Beginning <Table> and the ending </table> are not written, but all of the intervening <tr> S, <TH> S, and <TD> S are. the HTML output mode is envisioned as being useful for CGI.

Writing results to a file

By default, sqlite3 sends query results to standard output. you can change this using ". output "command. just put the name of an output file as an argument to. output command and all subsequent query results will be written to that file. use ". output stdout "to begin writing to standard output again. for example:

SQLite>. Mode list
SQLite>. Separator |
SQLite>. Output test_file_1.txt
SQLite>Select * From tbl1;
SQLite>. Exit
$Cat test_file_1.txt
Hello | 10
Goodbye | 20
$

Querying the database schema

The sqlite3 program provides several convenience commands that are useful for looking at the schema of the database. there is nothing that these commands do that cannot be done by some other means. these commands are provided purely as a shortcut cut.

For example, to see a list of the tables in the database, you can enter ". Tables ".

SQLite>. Tables
Tbl1
Tbl2
SQLite>

The ". Tables" command is similar to setting list mode then executing the following query:

SELECT name FROM sqlite_master WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'UNION ALL SELECT name FROM sqlite_temp_master WHERE type IN ('table','view') ORDER BY 1

In fact, if you look at the source code to the sqlite3 Program (found in the source tree in the file src/shell. c) You'll find exactly the above query.

The ". indices "command works in a similar way to list all of the indices for a particle table. the ". indices "command takes a single argument which is the name of the table for which the indices are desired. last, but not least, is ". schema "command. with no arguments, ". schema "command shows the original create table and create index statements that were used to build the current database. if you give the name of a table ". schema ", it shows the original create statement used to make that table and all if its indices. we have:

SQLite>. Schema
Create Table tbl1 (one varchar (10), two smallint)
Create Table tbl2 (
F1 varchar (30) primary key,
F2 text,
F3 real
)
SQLite>. Schema tbl2
Create Table tbl2 (
F1 varchar (30) primary key,
F2 text,
F3 real
)
SQLite>

The ". schema" command accomplishes the same thing as setting list mode, then entering the following query:

SELECT sql FROM    (SELECT * FROM sqlite_master UNION ALL    SELECT * FROM sqlite_temp_master)WHERE type!='meta'ORDER BY tbl_name, type DESC, name

Or, if you give an argument to ". schema" because you only want the schema for a single table, the query looks like this:

SELECT sql FROM   (SELECT * FROM sqlite_master UNION ALL    SELECT * FROM sqlite_temp_master)WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'ORDER BY substr(type,2,1), name

You can supply an argument to the. schema command. If you do, the query looks like this:

SELECT sql FROM   (SELECT * FROM sqlite_master UNION ALL    SELECT * FROM sqlite_temp_master)WHERE tbl_name LIKE '%s'  AND type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%'ORDER BY substr(type,2,1), name

The "% s" in the query is replace by your argument. This allows you to view the schema for some subset of the database.

SQLite>. Schema % ABC %

Along these same lines, ". table "command also accepts a pattern as its first argument. if you give an argument to. table command, a "%" is both appended and prepended and a like clause is added to the query. this allows you to list only those tables that match a participant pattern.

The ". databases "command shows a list of all databases open in the current connection. there will always be at least 2. the first one is "Main", the original database opened. the second is "Temp", the database used for temporary tables. there may be additional Databases listed for databases attached using the attach statement. the first output column is the name the database is attached with, and the second column is the filename of the external file.

SQLite>. Databases

Converting an entire database to an ASCII text file

Use the ". Dump" command to convert the entire contents of a database into a single ASCII text file. This file can be converted back into a database by piping it backSqlite3.

A good way to make an archival copy of a database is this:

$Echo '. dump' | sqlite3 ex1 | gzip-C> ex1.dump.gz

This generates a file namedEx1.dump.gzThat contains everything you need to reconstruct the database at a later time, or on another machine. to reconstruct the database, just type:

$Zcat ex1.dump.gz | sqlite3 ex2

The text format is pure SQL so you can also use the. Dump command to export an SQLite database into other popular SQL database engines. Like this:

$Createdb ex2
$Sqlite3 ex1. Dump | Psql ex2

Other dot commands

The ". explain "dot command can be used to set the output mode to" column "and to set the column widths to values that are reasonable for looking at the output of an explain command. the explain command is an SQLite-specific SQL extension that is useful for debugging. if any regular SQL is prefaced by explain, then the SQL command is parsed and analyzed but is not executed. instead, the sequence of virtual machine instructions that wocould have been used to execute the SQL command are returned like a query result. for example:

SQLite>. Explain
SQLite>Explain Delete from tbl1 where two <20;
ADDR opcode P1 P2 p3
---------------------------------------------------------------
0 listopen 0 0
1 open 0 1 tbl1
2 next 0 9
3 field 0 1
4 integer 20 0
5 GE 0 2
6 Key 0 0
7 listwrite 0 0
8 goto 0 2
9 Noop 0 0
10 listrewind 0 0
11 listread 0 14
12 Delete 0 0
13 goto 0 11
14 listclose 0 0

The ". Timeout" command sets the amount of time thatSqlite3Program will wait for locks to clear on files it is trying to access before returning an error. the default value of the timeout is zero so that an error is returned immediately if any needed database table or index is locked.

And finally, we mention the ". Exit" command which causes the sqlite3 program to exit.

Using sqlite3 in a shell script

One way to use sqlite3 in a shell script is to use "Echo" or "cat" to generate a sequence of commands in a file, then invoke sqlite3 while redirecting input from the generated command file. this works fine and is appropriate in your circumstances. but as an added convenience, sqlite3 allows a single SQL command to be entered on the command line as a second argument after the database name. when the sqlite3 program is launched with two arguments, the second argument is passed to the SQLite library for processing, the query results are printed on standard output in list mode, and the program exits. this mechanism is designed to make sqlite3 easy to use in conjunction with programs like "awk ". for example:

$Sqlite3 ex1 'select * From tbl1' |
>Awk '{printf "<tr> <TD> % S <TD> % s/n", $1, $2 }'
<Tr> <TD> Hello <TD> 10
<Tr> <TD> goodbye <TD> 20
$

Ending shell commands

SQLite commands are normally terminated by a semicolon. in the shell you can also use the word "go" (case-insensitive) or a slash character "/" on a line by itself to end a command. these are used by SQL Server and Oracle, respectively. these won't work inSqlite3_exec (), Because the shell translates these into a semicolon before passing them to that function.

Compiling the sqlite3 program from sources

The sqlite3 program is built automatically when you compile the SQLite library. Just get a copy of the source tree, Run "Configure" and then "make ".

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.