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

  • Posted November 27, 2014

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.


Submit an answer
You can type!ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

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:


# 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.