Pass parameters to MySQL script

后端 未结 6 2015
無奈伤痛
無奈伤痛 2020-12-09 04:05

I have a MySQL script file named query1.sql which contains:

select * FROM $(tblName) LIMIT 10;

I am in MySQL console, how do I

6条回答
  •  孤城傲影
    2020-12-09 04:32

    The advanced solution for use bash variables via mysql variables like @tblName in order to INSERT values into specific table:

    The core file insert.preps included prepared statements procedural (SET > PREPARE > EXECUTE > DEALLOCATE):

    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'; in the file predefined because id is usually is INT AUTO_INCREMENT PRIMARY KEY. It will auto-assign proper id for all lines.

    Invoking it in the shell or in bash script with using variables:

    mysql --defaults-extra-file=<(echo $'[client]\npassword='"$db_password") --user=$db_user $db_name -e "
         SET @tblName = '$table';
         SET @time = '$timeStamp';
         SET @file = '$file';
         SET @status = '$status';
    `cat /path/to/insert.preps`"
    

提交回复
热议问题