venkate
By:
venkate

How to read a set of strings and insert them into MySQL in terminal

November 27, 2014 1.3k views

Could someone share how to read a set of strings from terminal and insert them into MySQL in Ubuntu.

Kindly share a sample of code because i can be able to understand better.

1 Answer

If you are using shell scripting you can use the -e flag for the mysql command to directly run your query. So for instance if you wanted to grab the last line of your apache error log file and insert it into the field logline in a mysql table called errorlog on a database called logs you could use the following:

#!/bin/bash

# use tail to grab the last line of your log and assign it to the variable $lline
lline=`tail -1 /var/log/apache2/error`;

# run a mysql query to insert the value of $lline sending user (root) and password (mypass)
mysql -uroot -pmypass logs -e "INSERT INTO errorlog (logline) VALUES ('$lline')";

This is a very basic example and generally I would recommend doing some validation on the value before you insert it into your database and add some error handling but this should give you the general idea.

If you are using another language like perl or php you can use backticks around your command to execute it and return the result and then use the tools provided by the language you choose to handle your interaction with mysql.

Have another answer? Share your knowledge.