Erik's blog

Code, notes, recipes, general musings

updated Ruby utility for simple SQLite3 key/val storage

with one comment

motivation:

  • modify my previous sqlite utility to allow for table name definition & auto table creation

requirements/environment:

  • the requirements and environment are the same as in my previous post

code:

require 'rubygems'
require 'sqlite3'

class Storage
  def initialize
    @db = SQLite3::Database.new( 'sqlite' )
  end
  def create(table)
    begin
    @db.execute( %{
      CREATE TABLE #{table}
      (key varchar(100) PRIMARY KEY,
      value varchar(1000))
    } )
    rescue SQLite3::SQLException => details
      # puts details
    end
  end
  def use(table)
    @table = table
    self.create( table )
    return self
  end
  def get(key)
    results = @db.get_first_row( %{
      SELECT value FROM #{@table} WHERE key='#{key}'
    } )
    if results
      return results[0]
    end
  end
  def set(key, val)
    result = @db.execute( %{
      REPLACE INTO %s
      (key, value)
      VALUES ('%s', '%s')
    } % [@table, key, val ] )
  end
end

usage:

require 'rubygems'
require 'sqlite3'
require 'json'

Storage.new.use( 'user' ).set( 'user123', { :str => 'orale!' }.to_json )

json = Storage.new.use( 'user' ).get( 'user123' )

p JSON.parse json

notes:

  • DataMapper looks like it might provide much of this functionality. If my script’s complexity continues to increase, I’m inclined to incorporate a more sophisticated solution to run it. Thoughts?
Advertisements

Written by Erik

February 20, 2010 at 5:00 pm

Posted in code

Tagged with ,

One Response

Subscribe to comments with RSS.

  1. […] class is based on the SQLite utility class, YQL utility function, and simple key/val layer for YQL storage I recently posted.  The methods […]


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: