mysql2 gem支持可更新记录

时间:2014-08-11 17:48:28

标签: mysql ruby

mysql2 gem是否支持类似Microsoft-Access,可更新的记录集?

类似的东西:

client = Mysql2::Client.new(:host => "localhost", :username => "root", :database=> "db")

results = client.query("SELECT ... FROM ... WHERE ...;")

results.each do |row|

  # additional processing to calculate `a value`

  # set a column's value and update
  row["column_a"] = 'a value'
  row.save

end

client.close()

如果没有,那么我最好的选择是什么?

3 个答案:

答案 0 :(得分:3)

没有。您可以选择Arup建议的内容,也可以使用gem sequel来实现类似的功能

require 'sequel'

DB = Sequel.connect('mysql2://root@localhost/db')

class Post < Sequel::Model
end

Post.where(category: 'ruby').each do |post|
  post.title = 'StackOverflow'
  post.save
end

答案 1 :(得分:1)

您可以使用 RAW sql作为

require 'mysql'

begin
    con = Mysql2::Client.new(:host => "localhost", 
                             :username => "root", 
                             :database=> "db"
                             )   
    con.query "UPDATE table_name SET column_a = 'a value' WHERE <criterion>"
    puts "The query has affected #{con.affected_rows} rows" 
rescue Mysql::Error => e
    puts e    
ensure
    con.close if con
end

For INSERT, DELETE and UPDATE语句有一个名为#rows_affected的方法。此方法返回受这三个语句影响的行数

查看Test case examples宝石官方链接的mysql2

it "#last_id should return a Fixnum, the from the last INSERT/UPDATE" do
  @client.query "INSERT INTO lastIdTest (blah) VALUES (%s)" % [ client.escape(1234) ]
  @client.affected_rows.should eql(1)
  @client.query "UPDATE lastIdTest SET blah=4321 WHERE id=%s" % [ client.escape(1) ]
  @client.affected_rows.should eql(1)
end

答案 2 :(得分:-1)

如果你想要更新记录数量,试试这个,很简单:

require 'active_record'
require 'mysql2'

ActiveRecord::Base.transaction do
  Post.where(category: 'ruby').update_attributes(title: 'Stackoverflow')
end