Ruby SQLite数据库初始化

时间:2013-07-26 21:07:11

标签: ruby database sqlite

我正在尝试使用Ruby访问基本的SQLite数据库,但一直遇到一个奇怪的错误。 gems安装没有错误,我有正确的错误,但当我尝试实际运行代码时,我收到此错误:

/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

有什么可能导致这种情况的想法吗?

2 个答案:

答案 0 :(得分: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 :(得分: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