Tuesday, August 31, 2010

Testing sqlite3-ruby

# sqlite01.rb

require 'rubygems'
require 'sqlite3'

class SQLiteTest

 def initialize
  @db = SQLite3::Database.new("test.db")
  @db.execute("create table test (id INTEGER PRIMARY KEY, title TEXT)")\
    unless(table_exists("test"))
  @db.execute("insert into test (title) values('test1')")\
    unless(record_exists("test", "test1"))
  @db.execute("insert into test (title) values('test2')")\
    unless(record_exists("test", "test2"))
 end
 
 def table_exists(name)
  rows = @db.execute("select name from sqlite_master where name='"+name+"'")
  return (rows.count>0)
 end
 
 def record_exists(table_name, title)
  rows = @db.execute("select id from "+table_name+" where title='"+title+"'")
  return (rows.count>0)
 end
 
 def show_all
  rows = @db.execute('select * from test')
  p rows
 end
 
end

db = SQLiteTest.new
db.show_all

The result:
$ ruby sqlite01.rb 
[["1", "test1"], ["2", "test2"]]

No comments:

Post a Comment