gpt4 book ai didi

ruby - 为什么我的简单 Ruby SQLite3 示例失败了?

转载 作者:数据小太阳 更新时间:2023-10-29 08:41:24 26 4
gpt4 key购买 nike

在我尝试学习 Ruby 的过程中,我一直在阅读 Mr. Neighborly's Humble Little Ruby Book .

大多数示例都非常容易理解,让我很好地了解了 Ruby,但是我无法轻松运行与数据库相关的示例。

我正在尝试运行这段代码:(根据书中给出的示例稍作修改)

#!/usr/bin/ruby
require 'rubygems'
require 'dbi'

DBI.connect('DBI:SQLite3:testdb', 'ruby', 'ruby') do | dbh |
dbh.do('CREATE TABLE slugs(name varchar(20), age int);') rescue puts "TABLE slugs already exists."

sql = "INSERT INTO slugs (name, age) VALUES (?, ?)"

dbh.prepare(sql) do |st|
1.upto(20) do |i|
st.execute("slug #{i}", "#{i}")
end
end

end

运行时,它在数据库中插入一行,然后出现以下错误:

/var/lib/gems/1.8/gems/sqlite3-ruby-1.3.2/lib/sqlite3/statement.rb:41:in `bind_param': library routine called out of sequence (SQLite3::MisuseException)    from /var/lib/gems/1.8/gems/sqlite3-ruby-1.3.2/lib/sqlite3/statement.rb:41:in `bind_params'    from /var/lib/gems/1.8/gems/sqlite3-ruby-1.3.2/lib/sqlite3/statement.rb:37:in `each'    from /var/lib/gems/1.8/gems/sqlite3-ruby-1.3.2/lib/sqlite3/statement.rb:37:in `bind_params'    from /var/lib/gems/1.8/gems/dbd-sqlite3-1.2.5/lib/dbd/sqlite3/statement.rb:71:in `bind_params'    from /var/lib/gems/1.8/gems/dbi-0.4.5/lib/dbi/handles/statement.rb:115:in `execute'    from /media/dev/ruby-prax/moi.rb:12    from /media/dev/ruby-prax/moi.rb:11:in `upto'    from /media/dev/ruby-prax/moi.rb:11    from /var/lib/gems/1.8/gems/dbi-0.4.5/lib/dbi/handles/database.rb:61:in `prepare'    from /media/dev/ruby-prax/moi.rb:10    from /var/lib/gems/1.8/gems/dbi-0.4.5/lib/dbi/handles/driver.rb:41:in `connect'    from /var/lib/gems/1.8/gems/dbi-0.4.5/lib/dbi.rb:148:in `connect'    from /media/dev/ruby-prax/moi.rb:5TABLE slugs already exists.

我现在使用的是 Ubuntu 10.04。版本信息:

tlee@tim-ubuntu:/media/dev/ruby-prax$ ruby -vruby 1.8.7 (2010-01-10 patchlevel 249) [x86_64-linux]tlee@tim-ubuntu:/media/dev/ruby-prax$ gem list*** LOCAL GEMS ***abstract (1.0.0)daemons (1.1.0)dbd-mysql (0.4.4)dbd-odbc (0.2.5)dbd-sqlite3 (1.2.5)dbi (0.4.5)deprecated (3.0.0, 2.0.1)erubis (2.6.6)eventmachine (0.12.10)extlib (0.9.15)json_pure (1.4.6)mysql (2.8.1)rack (1.2.1)sqlite3-ruby (1.3.2)thin (1.2.7)thor (0.14.1)tlee@tim-ubuntu:/media/dev/ruby-prax$ sqlite3 --version3.6.22tlee@tim-ubuntu:/media/dev/ruby-prax$ 

我做错了什么?

最佳答案

我遇到了同样的问题。有一个 issue on github关于当您多次使用准备好的 INSERT 语句时 DBD 的 SQLite 驱动程序失败。就我个人而言,我已经在答案中采纳了移动到 RDBI 的建议。 ,因为 Ruby/DBI 显然不再被维护。迁移到 RDBI 只需要极少的代码更改。

关于ruby - 为什么我的简单 Ruby SQLite3 示例失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4253011/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com