开发者

writing to mysql table with ruby and generating absolutely unique id like youtube?

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.


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.


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

  • Ruby MySQL API
  • How to use it

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜