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

rubysqlite

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?

Thanks,

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 = SQLite3::Database.new 'file.db'

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

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

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