将参数传递给MySQL脚本

时间:2012-12-31 06:20:57

标签: mysql

我有一个名为query1.sql的MySQL脚本文件,其中包含:

select * FROM $(tblName) LIMIT 10;

我在MySQL控制台中,如何将参数传递给脚本?这不会转发变量:

mysql> \. query1.sql -v tblName=Users

6 个答案:

答案 0 :(得分:13)

您可以使用user variables来实现您描述的行为。当您将变量用作模式标识符而不是数据值时,您必须使用预准备语句,以便可以动态编写查询。

query1.sql

SET @query = CONCAT('Select * FROM ', @tblName, ' LIMIT 10');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

调用

mysql> SET @tblName = 'Users'; \. query1.sql

答案 1 :(得分:10)

来自vidyadhar的命令行调用对我有用,但只做了一点修改:

mysql -u root -p -e"set @temp=1; `cat /home/mysql/Desktop/a.sql`"

答案 2 :(得分:6)

这可能适合你

mysql -u root -p -e"set @temp=1;" < /home/mysql/Desktop/a.sql

mysql> set @temp=some_value;
mysql> source file.sql

这几乎与您的问题类似,只需尝试一下

答案 3 :(得分:1)

上面@ user4150422的回答几乎与我有关,但是cat给了我许可问题所以我不得不使用一个轻微的选择。很奇怪source命令也没有代替猫工作,但\.做了

mysql -u root -p -e"set @temp=1; `\. /home/mysql/Desktop/a.sql`"

答案 4 :(得分:1)

对于bash脚本:

hits = pg.sprite.spritecollide(player, platforms, False)
if hits:
    if player.pos.y == hits[0].rect.top:
        player.vel.y = 10
    else:
        player.pos.y = hits[0].rect.top + 1
        player.vel.y = 0

对于powershell:

tblName=$1 
searchFor="%something%"

echo "select * FROM $tblName LIMIT 10;
      select * From $tblName where somecolumn like '$searchFor';
" | mysql

答案 5 :(得分:0)

通过var results = (new List<BaseEntity>()).Concat(_context.Posts.ToList()); results = results.Concat(_context.Articles.ToList()).ToList(); //order //take(x) 之类的mysql变量使用bash变量以便将值插入特定表的高级解决方案:

核心文件insert.preps包含准备好的语句程序(SET> PREPARE> EXECUTE> DEALLOCATE):

with the_table (object, timestamp_start,timestamp_end ) as 
   ( values ('House', '2020-02-20 09:33:24'::timestamp, '2020-02-20 09:33:33'::timestamp)  
          , ('Dog',   '2020-02-20 18:00:03'::timestamp, '2020-02-21 18:33:22'::timestamp)  
          , ('Cat',   '2020-02-11 19:00:00'::timestamp, '2020-02-11 19:15:23'::timestamp)
          , ('Mouse', '2020-02-11 20:00:00'::timestamp, '2020-02-12 08:00:00'::timestamp)    
   )
select *
from the_table
where timestamp_start between  
      date_trunc('day', timestamp_start) + interval '18 hours' and 
      date_trunc('day', timestamp_start) + interval '1 day 9 hours' ; 
预定义文件中的

* @tblName,因为SET @query = CONCAT("INSERT INTO ", @tblName, " (id, time, file, status) VALUES (?, ?, ?, ?)"); PREPARE stmt FROM @query; SET @id = '0'; EXECUTE stmt USING @id, @time, @file, @status; DEALLOCATE PREPARE stmt; 通常是SET @id = '0';。它将自动为所有行分配正确的id

使用变量在shell或bash脚本中调用它:

INT AUTO_INCREMENT PRIMARY KEY