简体   繁体   English

如何通过SQL脚本,JDBC或Spring JdbcTemplate在MySQL中创建函数?

[英]How to create a function in MySQL from an SQL script, JDBC or Spring JdbcTemplate?

I'm looking for a way to create a function in MySQL preferably from a script ( executed from Java ) but standard JDBC or Spring's JdbcTemplate would work as well. 我正在寻找一种最好在MySQL中从脚本( 从Java执行 )创建函数的方法,但是标准JDBC或Spring的JdbcTemplate也可以工作。

I've managed to successfully create the function from mysql command-line console using: 我已经成功地使用以下命令从mysql命令行控制台成功创建了该函数:

DELIMITER $$
CREATE FUNCTION test() RETURNS double DETERMINISTIC
BEGIN
  RETURN 63;
END$$

But since DELIMITER in not a valid SQL syntax I get an exception when running it from a script: 但是由于DELIMITER使用的不是有效的SQL语法,因此从脚本运行它时会遇到异常:

[42000][1064] You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DELIMITER $$

When I try to create it from Spring JDBC template using 当我尝试使用Spring JDBC模板创建它时

jdbcTemplate.execute("CREATE FUNCTION some() RETURNS double DETERMINISTIC\n" +
            "BEGIN\n" +
            "RETURN 63;\n" +
            "END;");

I get the following exception: 我得到以下异常:

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 
'CREATE FUNCTION some() RETURNS double DETERMINISTIC
BEGIN
RETURN 63;
END' at line 1`

Does anyone know how to go about? 有人知道怎么做吗?

You can use jdbc to do that, but on your script don't declare any delimiter and then put your own one to separate functions or procedures declarations your script will look like : 您可以使用jdbc来执行此操作,但是在脚本上不要声明任何定界符,然后将自己的分隔符放在单独的函数或过程声明中,脚本将类似于:

CREATE FUNCTION do_something() RETURNS double DETERMINISTIC
BEGIN
  RETURN 63;
END;;
CREATE FUNCTION do_other_thing() RETURNS double DETERMINISTIC
BEGIN
  RETURN 63;
END;;

and the code to use will be like this after getting your sql script into a StringBuilder 将您的sql脚本放入StringBuilder后,使用的代码将像这样

 String[] sql = stringBuilder.toString().split(";;");
    for (int i = 0; i < sql.length; i++) {
                     statment.executeUpdate(sql[i]);
                }

I hope this ill help ! 希望对您有帮助!

使用Spring Framework时,请使用Hibernate Framework连接数据。

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

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