Ruby 请教 ruby 采用 mysql2 访问 mysql 如何插入特殊字符呢?

babodx · 2013年05月23日 · 最后由 babodx 回复于 2013年05月24日 · 3449 次阅读

我用 ruby 写一个小工具对比数据库表的记录,然后插入到另外一个表。 但是如果我插入的字段有特殊字符,就会造成语法错误。请问有什么办法解决吗?

我是从一个表里通过 r1=c1.query 将取到的记录集给 r1 然后 r1.each do |r| 去遍历插入 但是如何字段里有逗号,引号。程序就异常了。

c1.query("insert into cdb_typeoptionvars values ('#{r["sortid"]}','#{r["tid"]}','#{r["optionid"]}','#{r["expiration"]}','#{r["value"]}') ")

用 ActiveRecord 处理。

如果不用 ActiveRecord 就没办法了吗?记得原来用 mysql 的时候,有个 prepare 的方法,可以用?占位。然后后面再填充

用 escape:

c1.query("insert into ... ,'#{c1.escape r["value"]}') ")

以后会加入 prepared statement, 但现在还不行

恩。感谢。 最后还是用 ActiveRecord 了,还是这个简单好用。不过如果表格没有按照标准命名,有办法制定吗?

直接 base64 encode 后入库,出来再解一下,现在服务器这么强大,这点计算应该还是耗得起吧

其实最简单的方式是打开 phpMyAdmin,把你的内容插入一下,它会自动回显 php 的 sql 代码,这样你就知道哪些要转义了。

#6 楼 @Peter 感谢。看了很多你的视频,收获很大呀

#7 楼 @babodx 应该是谢谢 @happypeter 吧,他来晚了,Peter 归我了,呵呵

#7 楼 @babodx 对比数据库表的记录,插入到另外一个表是插入对比后相同的还是不同的记录呢?

程序已经搞定了。用了 activerecord,其实任务是一个 discuz 7.2 的论坛数据被误删除了一些,从早期的表里尝试恢复某个版块。下面是我最后的代码

require 'rubygems'
gem 'activerecord'

require 'mysql2'
require 'active_record'


ActiveRecord::Base.establish_connection(
  :adapter => 'mysql2',
  :database => 'sq_tvtv',
  :username => 'root',
  :password => 'root',
  :host => 'localhost',
  :encoding => 'utf8',
  :socket =>'/Applications/XAMPP/xamppfiles/var/mysql/mysql.sock'
)

class Cdb_thread < ActiveRecord::Base
end

class Cdb_typeoptionvar < ActiveRecord::Base
end

class Temp < ActiveRecord::Base
end

tids=Cdb_thread.all
puts "tids is num : #{tids.count}"

tids.each do |tid|
  #puts tid["tid"]
  vars=Cdb_typeoptionvar.where([ "tid = ?", tid["tid"]])
  if vars.count==0
      puts "fix tid : #{tid["tid"]}"
      ts=Temp.where(["tid = ?",tid["tid"]])
      if ts.count>0
        puts "found tid: #{tid["tid"]}"
        ts.each do |t|
          t1=Cdb_typeoptionvar.new
          t1.sortid=t["sortid"]
          t1.tid=t["tid"]
          t1.optionid=t["optionid"]
          t1.expiration=t["expiration"]
          t1.value=t["value"]
          t1.save
          puts "insert sortid : #{t["sortid"]}"
        end

      end

  end
end


需要 登录 后方可回复, 如果你还没有账号请 注册新账号