Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sqlite

ruby

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,

like image 606
banditKing Avatar asked Mar 28 '12 23:03

banditKing


People also ask

How do I connect to a SQLite database?

Installing sqlite3 module To connect to an SQLite database, you need to: First, import the sqlite3 module. Second, call the Database() function of the sqlite3 module and pass the database information such as database file, opening mode, and a callback function.

What is sqlite3 in Ruby?

sqlite3-ruby 1.3. 3This module allows Ruby programs to interface with the SQLite3 database engine (http://www.sqlite.org). You must have the SQLite engine installed in order to build this module. Note that this module is NOT compatible with SQLite 2.


1 Answers

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
like image 92
Matheus Moreira Avatar answered Oct 04 '22 12:10

Matheus Moreira