MySQL用户在shell脚本中定义的函数

时间:2017-05-21 07:10:33

标签: mysql function shell sh

我正在运行这个shell脚本:

root@user:/#sh myscript.sh

它包含以下代码:

#!/bin/bash -x
mysql -u username -password base1 << EOF
UPDATE table1 SET `trans` = translit (dn);

在输出中,我使用用户定义的函数translit得到错误。所有其他MySQL命令都已成功完成。在phpMyAdmin下,提到的命令正确运行。函数translit已正确定义。

2 个答案:

答案 0 :(得分:0)

here here中的反引号被解释为命令替换,并在woof ['meow'] bark ['meow', 'meow'] 运行之前由shell处理。引用分隔符以保护此处文档的内容不受shell处理。

mysql

(注意:我对MySQL不熟悉,知道反引号是否应该是单引号,或者是否需要引用。)

答案 1 :(得分:0)

尝试:

档案:myscript.sh

#!/bin/bash -x
mysql -u username -p -s << 'EOF'
USE `base1`;
SELECT `dn`, `trans` 
FROM `table1`;

UPDATE `table1`
SET `trans` = `translit`(`dn`);

SELECT CONCAT(REPEAT('*', 15), ' UPDATE ', REPEAT('*', 15));

SELECT `dn`, `trans`
FROM `table1`;
EOF
$ mysql -u username -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.7.11

Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> DROP DATABASE IF EXISTS `base1`;
Query OK, 1 row affected (0.00 sec)

mysql> CREATE DATABASE IF NOT EXISTS `base1`;
Query OK, 1 row affected (0.00 sec)

mysql> USE `base1`;
Database changed

mysql> DROP FUNCTION IF EXISTS `translit`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> DROP TABLE IF EXISTS `table1`;
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> CREATE TABLE IF NOT EXISTS `table1` (
    ->   `dn` VARCHAR(30) NOT NULL,
    ->   `trans` VARCHAR(30)
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> INSERT INTO `table1`
    ->   (`dn`)
    -> VALUES
    ->   ('Lorem Ipsum is simply dummy'),
    ->   ('text of the printing'),
    ->   ('and typesetting industry');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> CREATE FUNCTION `translit`(`_dn` VARCHAR(30))
    -> RETURNS VARCHAR(30) DETERMINISTIC
    -> RETURN REVERSE(`_dn`);
Query OK, 0 rows affected (0.00 sec)

mysql> \! ./myscript.sh
+ mysql -u root -p -s
Enter password: 
Lorem Ipsum is simply dummy NULL
text of the printing    NULL
and typesetting industry    NULL
*************** UPDATE ***************
Lorem Ipsum is simply dummy ymmud ylpmis si muspI meroL
text of the printing    gnitnirp eht fo txet
and typesetting industry    yrtsudni gnittesepyt dna
mysql>

请尝试4.6.6 mysql_config_editor — MySQL Configuration Utility不要泄露敏感信息。