简体   繁体   English

将参数传递给 MySQL 脚本命令行

[英]Pass parameter to MySQL script command line

Is there any option to pass a parameter from the command line to MySQL script?是否有任何选项可以将参数从命令行传递到 MySQL 脚本?

Something like @start_date in this example:在这个例子中像@start_date 这样的东西:

mysql –uuser_id -ppassword –h mysql-host -A -e 
"set @start_date=${start_date}; source ${sql_script};" >${data_file};

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:我们可以像这样传递 'start_date' 和 'end_date':

/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}

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: 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 :长答案:整个概念作为一个可运行的 bash ,mysql 应用程序:

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

or要么

    git clone git@github.com:YordanGeorgiev/mysql-starter.git

The "-e" option is sensible to the used quotes, try the double quote: "-e" 选项对使用的引号很合理,试试双引号:

mysql –uuser_id -ppassword –h mysql-host -A -e 
"set @start_date=\"$start_date\"; source \"$sql_script\";" >\"$data_file\";"

You may be able to avoid bash code in some cases by composing scripts together to run SQL code with different predefined arguments.在某些情况下,您可以通过将脚本组合在一起以运行具有不同预定义参数的 SQL 代码来避免使用 bash 代码。

For example:例如:

do-something-production.sql

USE mydb-prod;
SET @arg=5;
SOURCE do-something.sql;

do-something-test.sql : do-something-test.sql

USE mydb-test;
SET @arg=10;
SOURCE do-something.sql;

do-something.sql : do-something.sql :

UPDATE table SET col = (SELECT @arg);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM