0

I am trying to load data into mysql database using the following script

    #!/bin/bash

    DB_USER='my_user';
    DB_PASSWD='passwd';

    DB_NAME='db_name';
    TABLE='rass';

    INPUT_FILE='/full/path/to/re.txt';

    SQL="USE $DB_NAME; LOAD LOCAL DATA INFILE '$INPUT_FILE' REPLACE INTO TABLE `$TABLE` LINES TERMINATED BY '|' CHARACTER SET utf8;"
    mysql --user=$DB_USER --password=$DB_PASSWD --default_character_set utf8 $DB_NAME

When i run the command, it displays the mysql manual and none of the data in the file is inserted. Any ideas on how i can modify my code to insert the data

2 Answers 2

2

Use a here document.

mysql [args] << EOF
USE $DB_NAME; 
LOAD LOCAL DATA INFILE "$INPUT_FILE" REPLACE INTO TABLE "$TABLE" LINES TERMINATED BY '|' CHARACTER SET utf8;
QUIT;
EOF

(I suppose you don't want in fact single quotes around variables references).

Also, you might setup a ~/.my.cnf file so that non-interactive management is a bit simpler, for example:

[client]
user=root
password="some pass"
0

You can also use mysql -e and get Bash variables and put to MySQL query;

#!/bin/bash
baseName="base1"
tableName="table1"
animal="dog"
par1="1"
par2="2"

myslqquery="USE $baseName;
            INSERT INTO $tableName VALUES(NULL,\"$animal\",$par1,$par2);
            SELECT * from $tableName;"

mysql -uroot -e "$myslqquery"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .