Ruby – How to use Ruby to connect to a SQLite3 database outside of Rails as a scripting language


Hi Im using Ruby as a scripting language. Not for web development, but to connect to a local database on my computer and manipulate it.

Id like to know how I can connect. Do I need to download/import tools? What do I need to get started?


Best Solution

You need to install the sqlite3 gem:

gem install sqlite3

You can then use the library in your code. Here's an example, adapted from the project's README.rdoc file:

require 'sqlite3'

# Open a SQLite 3 database file
db = 'file.db'

# Create a table
result = db.execute <<-SQL
  CREATE TABLE numbers (
    name VARCHAR(30),
    val INT

# Insert some data into it
{ 'one' => 1, 'two' => 2 }.each do |pair|
  db.execute 'insert into numbers values (?, ?)', pair

# Find some records
db.execute 'SELECT * FROM numbers' do |row|
  p row