Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to MySQL script command line

Tags:

mysql

cmd

Is there any option to pass a parameter from the command line to MySQL script?

Something like @start_date in this example:

mysql –uuser_id -ppassword –h mysql-host -A -e 
"set @start_date=${start_date}; source ${sql_script};" >${data_file};
like image 219
danieln Avatar asked Apr 19 '12 13:04

danieln


2 Answers

Found an answer on the net here.

Basically, suppose that we want to run this query:

Select c_id, c_first_name,c_last_name, c_address,last_modified_date
from customer
where last_modified_date >=@start_date and last_modified_date <= @end_date;

We can pass 'start_date' and 'end_date' like this:

/usr/bin/mysql –uuser_id -ppassword –h mysql-host -A \
    -e "set @start_date=${start_date}; set @end_date=${end_date};\
        source ${sql_script};" > ${data_file}
like image 66
danieln Avatar answered Nov 07 '22 03:11

danieln


The Short answer:

bash :

        mysql -u"$mysql_user" -p"$mysql_user_pw" \
        -e "set @mysql_db='$mysql_db';source \
        00.create-mysql-starter-db.mysql ;" > "$tmp_log_file" 2>&1

mysql:

     SET @query = CONCAT('CREATE DATABASE /*!32312 IF NOT EXISTS*/ `'
     , @mysql_db , '` /*!40100 DEFAULT CHARACTER SET utf8 */') ; 
     -- SELECT 'RUNNING THE FOLLOWING query : ' , @query ; 
      PREPARE stmt FROM @query;
      EXECUTE stmt;
      DEALLOCATE PREPARE stmt;

The Long answer : The whole concept as a runnable bash , mysql app :

https://github.com/YordanGeorgiev/mysql-starter

or

    git clone [email protected]:YordanGeorgiev/mysql-starter.git
like image 20
Yordan Georgiev Avatar answered Nov 07 '22 03:11

Yordan Georgiev