关于Mycat调用存储过程

package com.text.jdbctest;

import java.sql.*;

public class JdbcTestLocalMysql {
    public static void main(String[] args) throws ClassNotFoundException {
        String storedProcedure = "/*!mycat: sql=SELECT 1 FROM person; */SET @ids:=11;call batchtest(@v_count,11); SELECT @v_count AS v_count;";

        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://localhost:8066/mysql";
        String user = "mysql";
        String password = "nDtZ7rHYjwM5";

        ResultSet resultSet = null;
        Class.forName(driver);

        try(Connection con = DriverManager.getConnection(url, user, password);){
            try(Statement  statement = con.createStatement();){
                resultSet = statement.executeQuery(storedProcedure);
                while (resultSet.next()){
                    System.out.println(resultSet.getString("v_count"));
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

执行后返回:

java.sql.SQLSyntaxErrorException: 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 'call batchtest(@v_count,11); SELECT @v_count AS v_count' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeQuery(StatementImpl.java:1198)
    at com.text.jdbctest.JdbcTestLocalMysql.main(JdbcTestLocalMysql.java:23)

Mycat版本:Mycat-server-1.6.76-test(GitHub源码)

MySQL版本:mysql8.0
 

原因有很多,你可以现在根据你的代码看看是哪一种。

1、单引号、反单引号分不清

java中键值用(‘)单引号,列名(`)反单引号。就是上面一排数字键最左边~符号那个,切换英文输入法即为反单引号。比如

int result = ed.insertData("insert into information(`nowtime`,`data`) values(current_time,'A');");


insertData就是负责执行这句SQL语句的,他最后返回受影响的条数,这个不用管。

其中列名分别是nowtime和data(这里用反单引号),写入数据库的值是current_time和字符A(这里用单引号)。

2、列名包括SQL关键字

解决办法:修改表名字,比如你的列名不能叫做update等关键字

3、语法错误

看看是不是少打空格了