SQLite is a lightweight, disk-based database that doesn’t require a separate server process, and allows access to the database using a nonstandard variant of the SQL query language. In this article, we will explore how to connect to and interact with SQLite databases using its command line interface (CLI).
What is SQLite?
SQLite is an embedded SQL database engine that is self-contained, serverless, and zero-configuration. It is widely used for local and small-scale data storage within applications. SQLite databases are stored in a single file on disk, which makes it easy to manage and portable across platforms.
Setting Up SQLite
Before we attempt to connect to an SQLite database, we need to install SQLite on our system. SQLite comes pre-installed on many Unix-based systems like macOS and Linux, but if it's not available, you will need to download it from the official SQLite website.
Opening SQLite Command-Line Interface
- Once SQLite is installed, open your terminal or command prompt window.
- To verify that SQLite is installed correctly, type the command:
sqlite3 --versionYou should see the version number of SQLite displayed if it's installed correctly.
Creating a New Database
To create a new SQLite database or connect to an existing one, use the following command:
sqlite3 database_name.dbIf 'database_name.db' does not exist, SQLite will create it for you. Once inside the SQLite prompt, you can execute SQL commands.
Basic SQLite Commands
Let's start with some basic SQLite commands:
-- Display all tables in the current database
.tables
-- Display the structure of a table
.schema table_name
-- Exit the SQLite command-line interface
.exitCreating a Table
To create a table within your database, use the following SQL command:
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT UNIQUE,
age INTEGER
);This command creates a table named 'users' with columns for id, name, email, and age.
Inserting Data
Once you have a table, you can insert data into it:
INSERT INTO users (name, email, age) VALUES ('Alice', '[email protected]', 30);
INSERT INTO users (name, email, age) VALUES ('Bob', '[email protected]', 25);Querying Data
To query data from a table, use the SELECT statement:
SELECT * FROM users;This command retrieves all rows from the 'users' table. Try more complex queries like filtering:
SELECT * FROM users WHERE age > 25;This will return users older than 25.
Using .help Command
The '.help' command in SQLite gives a list of available commands:
.helpThis will be useful as you explore more commands and features within SQLite.
Conclusion
SQLite provides a simple, efficient way to manage small-to-medium-size database applications directly from the command line. This makes it perfect for testing, development, and small apps without the overhead of a full SQL server. Mastering its command-line interface enables quick setup, inspection, and manipulation, greatly enhancing your productivity in managing SQLite databases.