Ruby Query MySQL Database

I have a sample table created in MySQL.

I have 3 functions
1. Connect to MySQL
2. Get all contacts
3. Insert contact

In my example, I am inserting 2 contacts and later retrieve the entire table of contacts.

Source code of the screenshot below

You can pass in the db connection as a parameter if you prefer to share the connection. I did not do that in the example. Running the ruby script will generate the output below

If you have problem adding mysql2 library, it is probably you have not install it with gem. Read my Ubuntu Install Nokogiri article for instructions on how to install the library.

< Back to all the stories I had written

A software engineer, a rock climbing, diving & inline skating enthusiast, a husband, a father.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store