code_junkie

How do you talk SQL directly to MySQL from Ruby?

Nov 13th, 2011
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. ActiveRecord::Base.connection.execute( some sql )
  2.  
  3. require 'mysql'
  4.  
  5. m = MySQL.new("localhost", "username", "password", "database")
  6. r = m.query("SELECT * FROM people ORDER BY name")
  7. r.each_hash do |f|
  8. print "#{f['name']} - #{f['email']}"
  9. end
  10.  
  11. require "dbi"
  12. require "dbi/dbrc"
  13.  
  14. # == Configuration
  15.  
  16. DB = "sympa"
  17. HOST = "saphir"
  18.  
  19. cnt = 0
  20. dup = 0
  21.  
  22. # == Crude option processing
  23. #
  24. list_name = ARGV.shift.to_s
  25. file = ARGV.shift.to_s
  26.  
  27. db = DBI::DBRC.new(DB)
  28. DBI.connect(db.dsn + ":#{HOST}", db.user, db.password) do |dbh|
  29. date = Time.now.asctime
  30.  
  31. if not list_name or list_name == "" then
  32. puts "List name is mandatory"
  33. exit 1
  34. end
  35.  
  36. req1 = <<-"EOR"
  37. insert into user_table (email_user,lang_user)
  38. values (?, ?)
  39. EOR
  40. ...
  41. req2 = <<-"EOR"
  42. insert into subscriber_table
  43. (user_subscriber, list_subscriber, visibility_subscriber,
  44. date_subscriber, reception_subscriber) values (?, ?, ?, NOW(), ?)
  45. EOR
  46.  
  47. sth1 = dbh.prepare(req1)
  48. sth2 = dbh.prepare(req2)
  49. ...
  50. #
  51. # Insertion in user_table
  52. #
  53. begin
  54. sth1.execute(line, "en")
  55. cnt += 1
  56. rescue DBI::DatabaseError => err
  57. $stderr.puts("DBI: #{err}")
  58. end
  59.  
  60. >> result = ActiveRecord::Base.connection.execute("SHOW TABLES")
  61. => #<Mysql::Result:0x37ecb30>
  62.  
  63. >> result.class.instance_methods - Object.instance_methods
  64. => ["all_hashes", "field_seek", "row_tell", "fetch_field_direct", "free", "field_tell", "fetch_lengths", "num_fields", "data_seek", "fetch_row", "num_rows", "fetch_field", "each", "each_hash", "fetch_hash", "row_seek", "fetch_fields"]
Add Comment
Please, Sign In to add comment