2013-07-26 88 views
0

我試圖用Ruby訪問基本的SQLite數據庫,但不斷收到一個奇怪的錯誤。寶石安裝沒有一個錯誤,我有適當的錯誤,但是當我嘗試實際運行的代碼,我得到這個錯誤:Ruby SQLite數據庫初始化

/home/--/.rvm/gems/ruby-2.0.0-p195/gems/sqlite3-1.3.7/lib/sqlite3/database.rb:91:in `initialize': near ".": syntax error (SQLite3::SQLException) 
from /home/mastelj/.rvm/gems/ruby-2.0.0-p195/gems/sqlite3-1.3.7/lib/sqlite3/database.rb:91:in `new' 
from /home/mastelj/.rvm/gems/ruby-2.0.0-p195/gems/sqlite3-1.3.7/lib/sqlite3/database.¦rb:91:in `prepare' 
from /home/mastelj/.rvm/gems/ruby-2.0.0-p195/gems/sqlite3-1.3.7/lib/sqlite3/database. rb:134:in `execute' 
^G Get Hel^O WriteOu^R Read Fi^Y Prev Pa^K Cut Tex^C Cur Pos from to_sqlite.rb:5:in `<main>' 

計劃

require 'sqlite3' 

db = SQLite3::Database.open('test.db') 
rows = db.execute(".tabes") 

for i in 0..rows.size-1 
    puts rows[i] 
end 

任何想法,以什麼可能導致此?

回答

1

嘗試:

db = SQLite3::Database.open('test.db') 
rows = db.execute("SELECT * FROM sqlite_master WHERE type='table';") 
# If you want just the table names do: 
rows = db.execute("SELECT name FROM sqlite_master WHERE type='table';") 

詳見上表SQLITE_MASTER這裏:http://www.sqlite.org/faq.html

1

SQL命令.tabes應該做什麼?

如果你使用一個有效的SQL,您可以使用db.execute

require 'sqlite3' 

db = SQLite3::Database.open('test.db') 
rows = db.execute("CREATE TABLE [test] ( [test] CHAR);") 

如果你想獲得你可能會選擇SQLITE_MASTER表的列表。

require 'sqlite3' 

db = SQLite3::Database.open('test.db') 
db.execute("CREATE TABLE [test] ( [test] CHAR);") 
rows = db.execute("SELECT * FROM sqlite_master WHERE type='table';") 
rows.each{|tab| 
    p tab 
} 

但我會推薦一個數據庫工具包,例如,續集:

require 'sequel' 
DB = Sequel.sqlite('test.db') 

DB.create_table(:test){ 
    String :content 
} 

puts DB.tables