Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash script to insert values in MySQL

I want to make a bash script that connects to my MySQL server and inserts some valuse from a txt file. I have written this down:

#!/bin/bash
echo "INSERT INTO test (IP,MAC,SERVER) VALUES ('cat test.txt');" | mysql -uroot -ptest test;

but I'm recieving the following error:

ERROR 1136 (21S01) at line 1: Column count doesn't match value count at row 1

I suppose the error is in my txt file, but I've tried many variations and still no hope of success.

My txt file looks like this:

10.16.54.29 00:f8:e5:33:22:3f marsara

like image 244
user2642601 Avatar asked Aug 01 '13 14:08

user2642601


People also ask

How to use insert into in MySQL?

When inserting a single row into the MySQL table, the syntax is as follows: INSERT INTO table_name(column_1,column_2,column_3) VALUES (value_1,value_2,value_3); In the INSERT INTO query, you should specify the following information: table_name : A MySQL table to which you want to add a new row.

Which command is used to insert data in a table in MySQL?

To insert data into a MySQL table, you would need to use the SQL INSERT INTO command. You can insert data into the MySQL table by using the mysql> prompt or by using any script like PHP.

What is the command to add data to the table?

The INSERT command is used to add new data into a table.

Which SQL command is used to insert a new row into a table?

The INSERT INTO statement is used to insert new records in a table.


1 Answers

Try this one:

#!/bin/bash
inputfile="test.txt"
cat $inputfile | while read ip mac server; do
    echo "INSERT INTO test (IP,MAC,SERVER) VALUES ('$ip', '$mac', '$server');"
done | mysql -uroot -ptest test;

This way you streaming the file read as well the mysql comand execution.

like image 148
fejese Avatar answered Sep 21 '22 08:09

fejese