sqlite 如何在Sequel中添加多列

vybvopom  于 2023-04-06  发布在  SQLite
关注(0)|答案(1)|浏览(137)

在本例中:

require 'rubygems'
require 'sqlite3'
require 'sequel'

db = SQLite3::Database.new "fruits.db"
db2 = Sequel.sqlite("fruits.db")

db.execute 'CREATE TABLE "fruit" ("box_id" INTEGER, "apples" INTEGER, "oranges" INTEGER, "total" INTEGER)'

db.execute "INSERT INTO fruit(box_id,apples,oranges) VALUES(1,2,2)"

thisBox = db2[:fruit][:box_id => 1]

这在SQLite3中起作用:

db.execute "UPDATE fruit SET total = apples + oranges WHERE box_id=1"

但我无法在续集的一行中找到相同的内容:

thisBox.update(:total => :apples + :oranges)

返回错误:

undefined method '+' for :unfollows:Symbol

我找到的唯一解决办法是:

apples = thisBox[:apples]
oranges = thisBox[:oranges]

thisBox.update(:total => apples + oranges)
kupeojn6

kupeojn61#

我强烈推荐阅读Sequel cheat sheetREADME和不同类的文档,它非常强大,在我看来,是一个很棒的ORM。
把它作为学习的起点,它也会展示一个简单但不是最有效的方法来做你所问的事情:

require 'sequel'

require 'logger'
DB = Sequel.sqlite(loggers: [Logger.new($stdout)])

DB.create_table :fruitbaskets do
  primary_key :id
  Integer :apple
  Integer :orange
  Integer :total
end

fruitbaskets = DB[:fruitbaskets]
fruitbaskets.insert(:apple => 1, :orange => 2, :total => 0)

fruit_basket = fruitbaskets.where(:id => 1)

fruit_basket.update(:total => fruit_basket.get([:apple, :orange]).sum) 

fruitbaskets.where(:id => 1).get([:apple, :orange, :total]) # => [1, 2, 3]
# >> I, [2019-11-04T19:30:20.524611 #8709]  INFO -- : (0.000188s) PRAGMA foreign_keys = 1
# >> I, [2019-11-04T19:30:20.524673 #8709]  INFO -- : (0.000013s) PRAGMA case_sensitive_like = 1
# >> I, [2019-11-04T19:30:20.525058 #8709]  INFO -- : (0.000228s) CREATE TABLE `fruitbaskets` (`id` integer NOT NULL PRIMARY KEY AUTOINCREMENT, `apple` integer, `orange` integer, `total` integer)
# >> I, [2019-11-04T19:30:20.525212 #8709]  INFO -- : (0.000060s) SELECT sqlite_version()
# >> I, [2019-11-04T19:30:20.525331 #8709]  INFO -- : (0.000036s) INSERT INTO `fruitbaskets` (`apple`, `orange`, `total`) VALUES (1, 2, 0)
# >> I, [2019-11-04T19:30:20.525477 #8709]  INFO -- : (0.000040s) SELECT `apple`, `orange` FROM `fruitbaskets` WHERE (`id` = 1) LIMIT 1
# >> I, [2019-11-04T19:30:20.525558 #8709]  INFO -- : (0.000023s) UPDATE `fruitbaskets` SET `total` = 3 WHERE (`id` = 1)
# >> I, [2019-11-04T19:30:20.525669 #8709]  INFO -- : (0.000037s) SELECT `apple`, `orange`, `total` FROM `fruitbaskets` WHERE (`id` = 1) LIMIT 1

注意事项:

fruit_basket = fruitbaskets.where(:id => 1)

fruit_basket.update(:total => fruit_basket.get([:apple, :orange]).sum)

Sequel允许我们增量地构建语句,如果它对我们的代码有用的话。我指向一个记录,然后可以以不同的方式重用变量。这真的很强大,在文档中有介绍。

相关问题