Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you talk SQL directly to MySQL from Ruby?

I want to write a script in Ruby to clean up some messed up keys in several copies of the same MySQL schema. I'd like to do something like SHOW CREATE TABLE, then look at what comes back and delete keys if they exist.

I know in the Rails environment you can do this...

ActiveRecord::Base.connection.execute( some sql )

But what you get back is a "Result" object. For this task I need a String so I can analyze it and act accordingly.

like image 884
Ethan Avatar asked Dec 26 '08 21:12

Ethan


People also ask

Is Ruby a MySQL connector?

The mysql2 Ruby gem provides an API for connecting to MySQL, performing queries, and iterating through results; it is intended to support MySQL 5.6, 5.7, and 8.0.

How do you connect to a database in Ruby?

In Ruby we can connect to database using DBI module. DBI module provides Database Independent Interface to access the data source. So, using DBI, the underlying data source can be any database like Oracle, MySQL, Postgres etc, however the API remains the same.


1 Answers

This should help you:

>> result = ActiveRecord::Base.connection.execute("SHOW TABLES")
=> #<Mysql::Result:0x37ecb30>

>> result.class.instance_methods - Object.instance_methods
=> ["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"]

Look at #all_hashes on the MySql::Result instance

like image 134
user52804 Avatar answered Sep 27 '22 20:09

user52804