Databases

Ruby SQLite

Using SQLite

Ruby SQLite uses sqlite3 gem for local databases.

Introduction to SQLite and Ruby

SQLite is a self-contained, serverless, and zero-configuration database engine. It is widely used for local database storage. In the Ruby ecosystem, the sqlite3 gem provides an interface to SQLite databases, making it easy to integrate database features into your Ruby applications.

Installing the sqlite3 Gem

Before you can use SQLite in Ruby, you need to install the sqlite3 gem. This gem acts as a bridge between Ruby and SQLite, allowing you to manage databases efficiently.

Install the gem by running the following command in your terminal:

Creating a Database

Once the sqlite3 gem is installed, you can create a new SQLite database. You can do this by establishing a connection to a new database file. If the file does not exist, SQLite will create it for you.

Here's how you can create a new database called example.db:

Creating Tables

With your database created, you can now create tables to store your data. The following example demonstrates how to create a table named users with columns for ID, name, and email.

Inserting Data into Tables

After creating a table, you can insert data into it. The example below shows how to insert a new user into the users table.

Querying the Database

To retrieve data from your database, you can execute SQL queries. The following example selects all entries from the users table and prints them to the console.

Updating and Deleting Records

Updating and deleting records in SQLite using Ruby is straightforward. Use SQL commands within the db.execute method. Here is an example of updating and deleting a record:

Closing the Database Connection

It's a good practice to close the database connection once you are done with database operations to free up resources. This can be done using the close method.

Conclusion

Using the sqlite3 gem in Ruby makes it easy to manage local databases. With a few lines of code, you can create databases, manage tables, and perform CRUD operations. This makes SQLite an excellent choice for small to medium-sized applications where simplicity and efficiency are required.

Previous
PostgreSQL