- How to connect to SQLite from the command line
- Connecting to SQLite from the command line
- More Information
- Connect to SQLite database (FireDAC)
- Contents
- Supported Versions
- Client Software
- Linux Client Software
- Driver Linkage
- Connection Definition Parameters
- 1. Getting Started
- 2. Double-click Startup On Windows
- 3. Special commands to sqlite3 (dot-commands)
- 4. Rules for «dot-commands»
- 5. Changing Output Formats
- 6. Querying the database schema
- 7. Redirecting I/O
- 7.1. Writing results to a file
- 7.2. Reading SQL from a file
- 7.3. File I/O Functions
- 7.4. The edit() SQL function
- 7.5. Importing CSV files
- 7.6. Export to CSV
- 7.6.1. Export to Excel
- 8. Accessing ZIP Archives As Database Files
- 8.1. How ZIP archive access is implemented
- 9. Converting An Entire Database To An ASCII Text File
- 10. Recover Data From a Corrupted Database
- 11. Loading Extensions
- 12. Cryptographic Hashes Of Database Content
- 13. Database Content Self-Tests
- 14. SQLite Archive Support
- 14.1. SQLite Archive Create Command
- 14.2. SQLite Archive Extract Command
- 14.3. SQLite Archive List Command
- 14.4. SQLite Archive Insert And Update Commands
- 14.5. Operations On ZIP Archives
- 14.6. SQL Used To Implement SQLite Archive Operations
- 15. SQL Parameters
- 16. Index Recommendations (SQLite Expert)
- 17. Other Dot Commands
- 18. Using sqlite3 in a shell script
- 19. Ending shell commands
- 20. Compiling the sqlite3 program from sources
- 20.1. Do-It-Yourself Builds
How to connect to SQLite from the command line
This article describes how to connect to SQLite from the command line using the sqlite3 program. You can use the sqlite3 program as a quick and easy way to access SQLite databases directly.
Connecting to SQLite from the command line
To connect to SQLite from the command line, follow these steps:
- Log in to your A2 Hosting account using SSH.
- At the command line, type the following command, replacing example.db with the name of the database file that you want to use:
After you access a database, you can use regular SQL statements to run queries, create tables, insert data, and more. Additionally:
- For SQLite show tables, type the following command at the sqlite> prompt:
To view the structure of a table, type the following command at the sqlite> prompt. Replace table with the name of the table that you want to view:
More Information
What is SQLite?
SQLite is a lightweight database management solution. It offers its users a high-performance, very dependable SQL database engine. SQLite’s code is available within public domain making it free for use for every private or commercial purpose. SQLite has been built into every mobile device and almost every computer. In fact, SQLite is the world’s most widely used database engine.
SQLite is a unique SQL solution because it doesn’t require a separate server process. Instead, it reads and writes right on disk files. A disk file contains a comprehensive SQL database complete with multiple tables, views and triggers. As a cross-platform file format, you are able to copy between 32-bit and 64-bit storage systems.
- Serverless
- Self-contained
- Zero-configuration
- Transactional
SQLite history
Software developer Dwayne Richard Hipp, while working for General Dynamics, wrote SQLite in early 2000 while on contract with the US Navy. SQLite was originally a Tcl extension. The goal of SQLite was to create a solution that didn’t require a database management solution or have the need for a database administrator. Hipp wrote the SQLite syntax close to that of PostgreSQL.
Источник
Connect to SQLite database (FireDAC)
This topic describes how to connect to SQLite database files.
Contents
Supported Versions
The FireDAC native driver supports SQLite database version 3.0 and later. For a detailed discussion on SQLite usage in FireDAC for a Delphi application, read the «Using SQLite with FireDAC» article.
Client Software
FireDAC supports two SQLite library linking modes:
- Static linking — the following client libraries are statically linked into the application:
- Win32 — sqlite3_x86.obj
- Win64 — sqlite3_x64.obj
- macOS64 — libcgsqlite3.dylib (requires deployment)
- iOSDevice64 — libsqlite.a
- Android32 — libsqlite.a
- Android64 — libsqlite.a
FireDAC provides SQLite binaries v 3.31.1.
- Dynamic linking — the following client libraries must be available in order to open a SQLite database:
- Win32 — x86 SQLITE3.DLL
- Win64 — x64 SQLITE3.DLL
- macOS64 — libsqlite3.dylib
- iOSDevice64 — libsqlite3.dylib
- Android32 — libsqlite.so
- Android64 — libsqlite.so
We recommend you to use versions 3.31.1 or later. That is the default mode for iOS Simulator.
You can download:
- The latest x86 DLL version from here, Chapter «Precompiled Binaries For Windows», item «This is a DLL» and place it in a folder listed in your PATH environment variable (for example, System32 folder) or in your application EXE folder.
- The x64 DLL version from here as «sqlite-netFx40-binary-x64-xxxxx.zip». Extract to a folder, copy SQLite.Interop.DLL into SQLITE3.DLL, then place it as above.
For SQLite, FireDAC adds the ability to choose static vs dynamic linkage of SQLite engine. To use the static linkage of SQLite engine it is required to add the unit FireDAC.Phys.SQLiteWrapper.Stat to the uses clause of one of the units of your project. Otherwise dynamical linkage will be chosen.
The TFDPhysSQLiteDriverLink.EngineLinkage property controls the linkage mode. When the value is slDefault or slStatic, then the FireDAC.Phys.SQLiteWrapper.Stat unit will be added at design-time to the unit hosting the component. If the application defines the connection at run-time, then the FireDAC.Phys.SQLiteWrapper.Stat unit must be added manually.
If the SQLite client library has not been installed properly, an exception is raised when you try to connect:
Linux Client Software
FireDAC on Linux supports only dynamic linking and requires the SQLite 3 client library. To install it:
- On Ubuntu Server 16.04 LTS, run:
Driver Linkage
To link the driver:
- drop a TFDPhysSQLiteDriverLink component from the «FireDAC Links» palette page
- or include the FireDAC.Phys.SQLite unit in an uses clause.
Connection Definition Parameters
To connect to a SQLite database, most applications require that you specify DriverID and Database (see Defining Connection (FireDAC) for details).
Parameter | Description | Example value | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Database |
| ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
OpenMode | ReadOnly | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Encrypt | Specifies a default encryption mode for a database. The mode may be overridden with an optional password prefix. If it is not specified, then the mode specified by this parameter is used. Otherwise, aes-256 is used. | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Password | Specifies a password for an encrypted database. The value may have the following form: [ aes-128 | aes-192 | aes-256 | aes-ctr-128 | aes-ctr-192 | aes-ctr-256 | aes-ecb-128 | aes-ecb-192 | aes-ecb-256 :] The optional prefix controls the cipher algorithm to be used. The default value is an empty string, which means the unencrypted mode. |
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
NewPassword | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
BusyTimeout | Sets an «ms» milliseconds to sleep when a table is locked and UpdateOptions.LockWait is set to True. Zero means do not wait. The default value is 10000. | 5000 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
CacheSize | Changes the maximum number of database disk pages that SQLite holds in memory at once. Each page uses about 1.5K of memory. The default value is 10000. | 10000 | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
SharedCache | Enables or disables the SQLite shared cache feature. For more details, read this. The default value is True. | False | |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
LockingMode | Off | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
ForeignKeys | Off | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
StringFormat | Unicode | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
GUIDFormat | Binary | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
DateTimeFormat | Binary | ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
Extensions |
Column | Contents |
---|---|
rootpgno | Even though it may not be possible to attribute the row to a specific database table, it may be part of a tree structure within the database file. In this case, the root page number of that tree structure is stored in this column. Or, if the page the row was found on is not part of a tree structure, this column stores a copy of the value in column «pgno» — the page number of the page the row was found on. In many, although not all, cases, all rows in the lost_and_found table with the same value in this column belong to the same table. |
pgno | The page number of the page on which this row was found. |
nfield | The number of fields in this row. |
id | If the row comes from a WITHOUT ROWID table, this column contains NULL. Otherwise, it contains the 64-bit integer rowid value for the row. |
c0, c1, c2. | The values for each column of the row are stored in these columns. The «.recover» command creates the lost_and_found table with as many columns as required by the longest orphaned row. |
If the recovered database schema already contains a table named «lost_and_found», the «.recover» command uses the name «lost_and_found0». If the name «lost_and_found0» is also already taken, «lost_and_found1», and so on. The default name «lost_and_found» may be overridden by invoking «.recover» with the —lost-and-found switch. For example, to have the output script call the table «orphaned_rows»:
11. Loading Extensions
You can add new custom application-defined SQL functions, collating sequences, virtual tables, and VFSes to the command-line shell at run-time using the «.load» command. First, convert the extension in to a DLL or shared library (as described in the Run-Time Loadable Extensions document) then type:
Note that SQLite automatically adds the appropriate extension suffix («.dll» on windows, «.dylib» on Mac, «.so» on most other unixes) to the extension filename. It is generally a good idea to specify the full pathname of the extension.
SQLite computes the entry point for the extension based on the extension filename. To override this choice, simply add the name of the extension as a second argument to the «.load» command.
Source code for several useful extensions can be found in the ext/misc subdirectory of the SQLite source tree. You can use these extensions as-is, or as a basis for creating your own custom extensions to address your own particular needs.
12. Cryptographic Hashes Of Database Content
The «.sha3sum» dot-command computes a SHA3 hash of the content of the database. To be clear, the hash is computed over the database content, not its representation on disk. This means, for example, that a VACUUM or similar data-preserving transformation does not change the hash.
The «.sha3sum» command supports options «—sha3-224», «—sha3-256», «—sha3-384», and «—sha3-512» to define which variety of SHA3 to use for the hash. The default is SHA3-256.
The database schema (in the sqlite_schema table) is not normally included in the hash, but can be added by the «—schema» option.
The «.sha3sum» command takes a single optional argument which is a LIKE pattern. If this option is present, only tables whose names match the LIKE pattern will be hashed.
The «.sha3sum» command is implemented with the help of the extension function «sha3_query()» that is included with the command-line shell.
13. Database Content Self-Tests
The «.selftest» command attempts to verify that a database is intact and is not corrupt. The .selftest command looks for a table in schema named «selftest» and defined as follows:
The .selftest command reads the rows of the selftest table in selftest.tno order. For each ‘memo’ row, it writes the text in ‘cmd’ to the output. For each ‘run’ row, it runs the ‘cmd’ text as SQL and compares the result to the value in ‘ans’, and shows an error message if the results differ.
If there is no selftest table, the «.selftest» command runs PRAGMA integrity_check.
The «.selftest —init» command creates the selftest table if it does not already exists, then appends entries that check the SHA3 hash of the content of all tables. Subsequent runs of «.selftest» will verify that the database has not been changed in any way. To generates tests to verify that a subset of the tables are unchanged, simply run «.selftest —init» then DELETE the selftest rows that refer to tables that are not constant.
14. SQLite Archive Support
The «.archive» dot-command and the «-A» command-line option provide built-in support for the SQLite Archive format. The interface is similar to that of the «tar» command on unix systems. Each invocation of the «.ar» command must specify a single command option. The following commands are available for «.archive»:
Option | Long Option | Purpose |
---|---|---|
-c | —create | Create a new archive containing specified files. |
-x | —extract | Extract specified files from archive. |
-i | —insert | Add files to existing archive. |
-t | —list | List the files in the archive. |
-u | —update | Add files to existing archive if they have changed. |
As well as the command option, each invocation of «.ar» may specify one or more modifier options. Some modifier options require an argument, some do not. The following modifier options are available:
Option | Long Option | Purpose |
---|---|---|
-v | —verbose | List each file as it is processed. |
-f FILE | —file FILE | If specified, use file FILE as the archive. Otherwise, assume that the current «main» database is the archive to be operated on. |
-a FILE | —append FILE | Like —file, use file FILE as the archive, but open the file using the apndvfs VFS so that the archive will be appended to the end of FILE if FILE already exists. |
-C DIR | —directory DIR | If specified, interpret all relative paths as relative to DIR, instead of the current working directory. |
-n | —dryrun | Show the SQL that would be run to carry out the archive operation, but do not actually change anything. |
— | — | All subsequent command line words are command arguments, not options. |
For command-line usage, add the short style command-line options immediately following the «-A», without an intervening space. All subsequent arguments are considered to be part of the .archive command. For example, the following commands are equivalent:
Long and short style options may be mixed. For example, the following are equivalent:
Alternatively, the first argument following to «.ar» may be the concatenation of the short form of all required options (without the «-» characters). In this case arguments for options requiring them are read from the command line next, and any remaining words are considered command arguments. For example:
14.1. SQLite Archive Create Command
Create a new archive, overwriting any existing archive (either in the current «main» db or in the file specified by a —file option). Each argument following the options is a file to add to the archive. Directories are imported recursively. See above for examples.
14.2. SQLite Archive Extract Command
Extract files from the archive (either to the current working directory or to the directory specified by a —directory option). If there are no arguments following the options all files are extracted from the archive. Or, if there are arguments, they are the names of files to extract from the archive. Any specified directories are extracted recursively. It is an error if any specified files are not part of the archive.
14.3. SQLite Archive List Command
List the contents of the archive. If no arguments are specified, then all files are listed. Otherwise, only those specified as arguments are. Currently, the —verbose option does not change the behaviour of this command. That may change in the future.
14.4. SQLite Archive Insert And Update Commands
The —update and —insert commands work like —create command, except that they do not delete the current archive before commencing. New versions of files silently replace existing files with the same names, but otherwise the initial contents of the archive (if any) remain intact.
For the —insert command, all files listed are inserted into the archive. For the —update command, files are only inserted if they do not previously exist in the archive, or if their «mtime» or «mode» is different from what is currently in the archive.
Compatibility node: Prior to SQLite version 3.28.0 (2019-04-16) only the —update option was supported but that option worked like —insert in that it always reinserted every file regardless of whether or not it had changed.
14.5. Operations On ZIP Archives
If FILE is a ZIP archive rather than an SQLite Archive, the «.archive» command and the «-A» command-line option still work. This is accomplished using of the zipfile extension. Hence, the following commands are roughly equivalent, differing only in output formatting:
Traditional Command | Equivalent sqlite3.exe Command |
---|---|
unzip archive.zip | sqlite3 -Axf archive.zip |
unzip -l archive.zip | sqlite3 -Atvf archive.zip |
zip -r archive2.zip dir | sqlite3 -Acf archive2.zip dir |
14.6. SQL Used To Implement SQLite Archive Operations
The various SQLite Archive Archive commands are implemented using SQL statements. Application developers can easily add SQLite Archive Archive reading and writing support to their own projects by running the appropriate SQL.
To see what SQL statements are used to implement an SQLite Archive operation, add the —dryrun or -n option. This causes the SQL to be displayed but inhibits the execution of the SQL.
The SQL statements used to implement SQLite Archive operations make use of various loadable extensions. These extensions are all available in the SQLite source tree in the ext/misc/ subfolder. The extensions needed for full SQLite Archive support include:
fileio.c — This extension adds SQL functions readfile() and writefile() for reading and writing content from files on disk. The fileio.c extension also includes fsdir() table-valued function for listing the contents of a directory and the lsmode() function for converting numeric st_mode integers from the stat() system call into human-readable strings after the fashion of the «ls -l» command.
sqlar.c — This extension adds the sqlar_compress() and sqlar_uncompress() functions that are needed to compress and uncompress file content as it is insert and extracted from an SQLite Archive.
zipfile.c — This extension implements the «zipfile(FILE)» table-valued function which is used to read ZIP archives. This extension is only needed when reading ZIP archives instead of SQLite archives.
appendvfs.c — This extension implements a new VFS that allows an SQLite database to be appended to some other file, such as an executable. This extension is only needed if the —append option to the .archive command is used.
15. SQL Parameters
SQLite allows bound parameters to appear in an SQL statement anywhere that a literal value is allowed. The values for these parameters are set using the sqlite3_bind_. () family of APIs.
Parameters can be either named or unnamed. An unnamed parameter is a single question mark («?»). Named parameters are a «?» followed immediately by a number (ex: «?15» or «?123») or one of the characters «$», «:», or «@» followed by an alphanumeric name (ex: «$var1», «:xyz», «@bingo»).
This command-line shell leaves unnamed parameters unbound, meaning that they will have a value of an SQL NULL, but named parameters might be assigned values. If there exists a TEMP table named «sqlite_parameters» with a schema like this:
And if there is an entry in that table where the key column exactly matches the name of parameter (including the initial «?», «$», «:», or «@» character) then the parameter is assigned the value of the value column. If no entry exists, the parameter defaults to NULL.
The «.parameter» command exists to simplify managing this table. The «.parameter init» command (often abbreviated as just «.param init») creates the temp.sqlite_parameters table if it does not already exist. The «.param list» command shows all entries in the temp.sqlite_parameters table. The «.param clear» command drops the temp.sqlite_parameters table. The «.param set KEY VALUE» and «.param unset KEY» commands create or delete entries from the temp.sqlite_parameters table.
The temp.sqlite_parameters table only provides values for parameters in the command-line shell. The temp.sqlite_parameter table has no effect on queries that are run directly using the SQLite C-language API. Individual applications are expected to implement their own parameter binding. You can search for «sqlite_parameters» in the command-line shell source code to see how the command-line shell does parameter binding, and use that as a hint for how to implement it yourself.
16. Index Recommendations (SQLite Expert)
Note: This command is experimental. It may be removed or the interface modified in incompatible ways at some point in the future.
For most non-trivial SQL databases, the key to performance is creating the right SQL indexes. In this context «the right SQL indexes» means those that cause the queries that an application needs to optimize run fast. The «.expert» command can assist with this by proposing indexes that might assist with specific queries, were they present in the database.
The «.expert» command is issued first, followed by the SQL query on a separate line. For example, consider the following session:
In the above, the user creates the database schema (a single table — «x1»), and then uses the «.expert» command to analyze a query, in this case «SELECT * FROM x1 WHERE a=? AND b>?». The shell tool recommends that the user create a new index (index «x1_idx_000123a7») and outputs the plan that the query would use in EXPLAIN QUERY PLAN format. The user then creates an index with an equivalent schema and runs the analysis on the same query again. This time the shell tool does not recommend any new indexes, and outputs the plan that SQLite will use for the query given the existing indexes.
The «.expert» command accepts the following options:
Option | Purpose |
---|---|
—verbose | If present, output a more verbose report for each query analyzed. |
—sample PERCENT | By default, the «.expert» command recommends indexes based on the query and database schema alone. This is similar to the way the SQLite query planner selects indexes for queries if the user has not run the ANALYZE command on the database to generate data distribution statistics. Th functionality described in this section may be integrated into other applications or tools using the SQLite expert extension code. 17. Other Dot CommandsThere are many other dot-commands available in the command-line shell. See the «.help» command for a complete list for any particular version and build of SQLite. 18. Using sqlite3 in a shell scriptOne 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 many 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: 19. Ending shell commandsSQLite 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 in sqlite3_exec(), because the shell translates these into a semicolon before passing them to that function. 20. Compiling the sqlite3 program from sourcesTo compile the command-line shell on unix systems and on Windows with MinGW, the usual configure-make command works: The configure-make works whether your are building from the canonical sources from the source tree, or from an amalgamated bundle. There are few dependencies. When building from canonical sources, a working tclsh is required. If using an amalgamation bundle, all the preprocessing work normally done by tclsh will have already been carried out and only normal build tools are required. A working zlib compression library is needed in order for the .archive command to operate. On Windows with MSVC, use nmake with the Makefile.msc: For correct operation of the .archive command, make a copy of the zlib source code into the compat/zlib subdirectory of the source tree and compile this way: 20.1. Do-It-Yourself BuildsThe source code to the sqlite3 command line interface is in a single file named «shell.c». The shell.c source file is generated from other sources, but most of the code for shell.c can be found in src/shell.c.in. (Regenerate shell.c by typing «make shell.c» from the canonical source tree.) Compile the shell.c file (together with the sqlite3 library source code) to generate the executable. For example: The following additional compile-time options are recommended in order to provide a full-featured command-line shell: Источник |