Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH - How to read file contents to insert results into mysql WHERE clause

I'm trying to make a file (call it accounts) and have a bash script (call it *name_checker*) loop through each line and make it into multiple strings to store in a variable called '$NAMES' for a mysql WHERE IN clause

For example:

My query in my script *name_checker* is basic:

SELECT * FROM table WHERE account_name IN ('$NAMES')

The values for the IN statement will need to be separated by commas and put into single quotes.

My accounts file will be names separated by newlines:

NAME1

NAME2

NAME3

So I would need my script (*name_checker*) to get rid of the newlines and surround each name with single quotes and separate them with a comma. The desired results when the script is run would be

SELECT * FROM table WHERE account_name IN ('NAME1','NAME2','NAME3')

I am having some difficulty with this and I'm not too familiar with using sed. Help is appreciated!

like image 462
Walker Boh Avatar asked Jun 08 '13 18:06

Walker Boh


People also ask

How can I add values to one column in a table in MySQL?

In syntax, First, you must specify the name of the table. After that, in parenthesis, you must specify the column name of the table, and columns must be separated by a comma. The values that you want to insert must be inside the parenthesis, and it must be followed by the VALUES clause.

What is into Outfile in MySQL?

INTO OUTFILE is the complement of LOAD DATA . Column values are written converted to the character set specified in the CHARACTER SET clause. If no such clause is present, values are dumped using the binary character set. In effect, there is no character set conversion.

How can I add multiple values in one column in MySQL?

MySQL INSERT multiple rows statement In this syntax: First, specify the name of table that you want to insert after the INSERT INTO keywords. Second, specify a comma-separated column list inside parentheses after the table name. Third, specify a comma-separated list of row data in the VALUES clause.


1 Answers

It can be done without calling external utilities.

cat >Accounts.txt <<XXX
NAME1
NAME2
NAME3
XXX

Script:

while read x; do NAMES="$NAMES,'$x'"; done <Accounts.txt
NAMES=${NAMES:1}
SQL='SELECT * FROM table WHERE account_name IN ('$NAMES')'
echo "$SQL"

Output:

SELECT * FROM table WHERE account_name IN ('NAME1','NAME2','NAME3')

Or it can be even simplified removing explicit loop

printf -v NAMES ",'%s'" $(<Accounts.txt)
NAMES=${NAMES:1}
echo "$NAMES";

Output:

'NAME1','NAME2','NAME3'
like image 181
TrueY Avatar answered Sep 28 '22 14:09

TrueY