简体   繁体   中英

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.

I've managed to successfully create the function from mysql command-line console using:

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:

[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

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 :

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

 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连接数据。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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