This tutorials guides you to go straight into interacting with MySQL database using Ruby alone. No Rails. It is assumed that MySQL has been installed in your computer.
Now let’s get started:
First of all, lets begin with installing MySQL libraries via RubyGems
There is documentation for the MySQL library online . So you can follow that.
Now let’s fire irb.
If you are using something like Lampp you may end up with error like
So you have to locate where your mysqld.sock is.
For Lamp users, it’s in /opt/lampp/var/mysql/mysql.sock For others you can find by using ps aux | grep mysql
Next,create symlink at ‘/var/run/mysqld/mysqld.sock’ to location of mysql.sock by ln -s command.
That’s it. Now we are ready to go. With successfull connection we can query to database.
1 2 3 4 5 6 7 8 9 10
The code is wrapped up in an exception handling block, to ensure that no matter what happens in the code. The database connection is closed.
The returned result is of Mysql::Result class.Check the documentation and scroll down to Mysql::Result for various methods available at your disposal.If you are familiar with other MySQL connectors, this should be a breeze.
Lastly, Mysql Ruby connector also supports prepared statements, so you can use goodness out of it.
1 2 3 4 5 6 7 8 9 10 11 12 13