Databases

Crystal SQLite

Using SQLite

Crystal SQLite uses crystal-sqlite3 for local database queries.

Introduction to Crystal SQLite3

Crystal SQLite allows developers to interact with local SQLite databases using the crystal-sqlite3 library. This library provides a simple and efficient way to manage SQLite databases in your Crystal applications. In this guide, we will explore how to set up and run queries against an SQLite database using Crystal.

Installing crystal-sqlite3

Before you can start using SQLite with Crystal, you need to install the crystal-sqlite3 shard. You can add it to your project's shard.yml file as follows:

After adding the dependency, run the following command to install it:

Connecting to an SQLite Database

Once the shard is installed, you can connect to an SQLite database by creating a new instance of SQLite3::Database. Here's how you can open a connection to a database file:

Creating a Table

With the database connection established, you can execute SQL commands to create tables. The following code snippet creates a simple table named users:

Inserting Data

After creating tables, you can insert data into them. This example demonstrates how to insert a new user into the users table:

Querying Data

To retrieve data from the database, you can use the query method. Here's an example of querying all users:

Closing the Database Connection

Once you are done with the database operations, it's important to close the database connection to free up resources:

By following these steps, you can effectively manage SQLite databases within your Crystal applications. The crystal-sqlite3 shard makes it easy to perform various database operations efficiently.

Previous
PostgreSQL