如何将变量传递给 mysql 脚本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/76065/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 12:01:09  来源:igfitidea点击:

How do I pass a variable to a mysql script?

mysqlvariablesscripting

提问by Tom Burke

I know that with mysql you can write SQL statements into a .sql file and run the file from the mysql command line like this:

我知道使用 mysql 您可以将 SQL 语句写入 .sql 文件并从 mysql 命令行运行该文件,如下所示:

mysql> source script.sql

How do I pass a variable to the script? For example, if I want to run a script that retrieves all the employees in a department, I want to be able to pass in the number of the department as a variable.

如何将变量传递给脚本?例如,如果我想运行一个脚本来检索某个部门的所有员工,我希望能够将部门编号作为变量传入。

I am not trying to run queries through a shell script. There are simple queries I run from the mysql command line. I'm tired of retyping them all the time, and writing a shell script for them would be overkill.

我不想通过 shell 脚本运行查询。我从 mysql 命令行运行了一些简单的查询。我厌倦了一直重新输入它们,为它们编写一个 shell 脚本是多余的。

采纳答案by Brad Choate

Like this:

像这样:

set @department := 'Engineering';

Then, reference @departmentwherever you need to in script.sql:

然后,@department在 script.sql 中引用您需要的任何位置:

update employee set salary = salary + 10000 where department = @department;

回答by Yordan Georgiev

    #!/bin/bash

    #verify the passed params
    echo 1 cmd arg : 
    echo 2 cmd arg : 

    export db=
    export tbl=

    #set the params ... Note the quotes ( needed for non-numeric values )
    mysql -uroot -pMySecretPaassword \
    -e "set @db='${db}';set @tbl='${tbl}';source run.sql ;" ;

    #usage: bash run.sh my_db my_table
    #
    #eof file: run.sh

    --file:run.sql

    SET @query = CONCAT('Select * FROM ', @db , '.' , @tbl ) ;
    SELECT 'RUNNING THE FOLLOWING query : ' , @query ;
    PREPARE stmt FROM @query;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

    --eof file: run.sql

you can re-use the whole concept from from the following project

您可以重用以下项目中的整个概念

回答by longneck

you really should be looking at a more appropriate way of doing this. i'm going to guess that you're trying to run mysql queries via a shell script. you should instead be using something like PERL or PHP.

你真的应该寻找一种更合适的方式来做到这一点。我猜你想通过 shell 脚本运行 mysql 查询。你应该改用 PERL 或 PHP 之类的东西。