0

how can i write to a mysql table with ruby ? run SQL. for example, if the ruby script finishes, write to mysql table saying its done and how can i generate an absolutely unique ID ? kinda like youtube's id.

pweujzn
  • 3
  • 2

2 Answers2

1

Here's everything you'd want to know about connecting to MySQL from Ruby:

If you're looking for just a unique ID, and you don't mind exposing an obviously incrementing integer to the world, assign an autoincrement integer field to your table. I added the "and you don't mind" part because anyone who looks at your ID will be able to guess the scheme and will likely experiment fetching nearby integers.

If you want a truly random string to use as your ID (which is more Youtube-ish), check out this discussion.

Community
  • 1
  • 1
Mark Westling
  • 5,678
  • 4
  • 24
  • 29
1

For the unique ID, it's pretty easy. You should take a look at mysql's auto increment.

For mysql with Ruby, you need to use the mysql gem.
Using it is also pretty easy. You could do something like the following :

require "mysql"

begin
    # connect to the MySQL server
    dbh = Mysql.real_connect("localhost", "root", "password", "database")

    dbh.query("INSERT INTO database (field) VALUES ('value')")
rescue Mysql::Error => e
    p "Error code: #{e.errno}"
    p "Error message: #{e.error}"
    p "Error SQLSTATE: #{e.sqlstate}" if e.respond_to?("sqlstate")
ensure
    # disconnect from server
    dbh.close if dbh
end

And if you're planning to build something consequent, you might also be interested in using Active Record.

Damien MATHIEU
  • 29,275
  • 12
  • 79
  • 89