解决JDBC中Parameter number X is not an OUT parameter
话不多数,直接上码!
mysql语句如下:
DELIMITER $$
CREATE PROCEDURE QUERY_NAME(IN eid INT,OUT ename VARCHAR(20))
BEGIN
SELECT name into ename FROM javaee.employee WHERE id=eid;
END $$
DELIMITER;
java重要源码如下
//以下是从配置文件获取数据库的参数
properties.load(new FileInputStream("./src/jdbc.properties"));
url = properties.getProperty("url");
user = properties.getProperty("user");
password = properties.getProperty("password");
driverClass = properties.getProperty("driverClass");
//以下是调用存储过程
String sql = "CALL QUERY_NAME(?,?)";
connection = JdbcUtil.getConnection();
callStatement = connection.prepareCall(sql);
// 设置输入参数
callStatement.setInt(1, 1);
// 设置输出参数
callStatement.registerOutParameter(2, java.sql.Types.VARCHAR);
// 发送sql
callStatement.executeQuery();
// 获取结果
String name = callStatement.getString(2);
System.out.println(name);
运行后出现如下问题
java.sql.SQLException: Parameter number 2 is not an OUT parameter
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:965)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:898)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:887)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:861)
at com.mysql.jdbc.CallableStatement.checkIsOutputParam(CallableStatement.java:630)
at com.mysql.jdbc.CallableStatement.registerOutParameter(CallableStatement.java:1807)
at better.cool.test3.Test3.main(Test3.java:27)
仔细排查后,发现是没有指定数据库的原因,解决方法有两种:
(1)在连接数据库时,指定数据库,如 url=jdbc:mysql://localhost:3306/javaee
其中javaee为指定的数据库,只需要把存储过程存在这个数据库里即可。
(2)在写sql语句时指定数据库,如 CALL javaee.QUERY_NAME(?,?)
希望以上可以帮助大家不要踩坑,不然真的要找好久才会恍然大悟。