java.sql.SQLException: Parameter index out of range

Mysql创建存储过程:

create procedure s_add(in a int, in b int, out sum int)  
begin  
    set sum = a + b;  
end

之后这是Java代码

package ch04.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Types;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CstmtExample extends HttpServlet{
    private String url;
    private String user;
    private String password;
    public void init() throws ServletException {
        ServletContext sc = getServletContext();
        String driverClass = sc.getInitParameter("driverClass");
        url = sc.getInitParameter("url");
        user = sc.getInitParameter("user");
        password = sc.getInitParameter("password");
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }        
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Connection conn = null;
        CallableStatement cstmt = null;
        try {
            conn = DriverManager.getConnection(url, user, password);
            cstmt = conn.prepareCall("{call s_add(?, ?, ?)}");
            cstmt.setInt(1, 5);
            cstmt.setInt('b', 6);
            cstmt.registerOutParameter(3, Types.INTEGER);
            cstmt.execute();
            int ret = cstmt.getInt(3);
            PrintWriter out = resp.getWriter();
            out.println(ret);
            out.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }    
    }
}

连接没问题,就是对于控制台输出的报错不知道怎么改?

java.sql.SQLException: Parameter index out of range (98 > number of parameters, which is 3).
    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)

这是控制台报错。

慕姐4208626
浏览 985回答 2
2回答

FFIVE

cstmt.setInt('b', 6);是什么?‘b’十进制是98 改为 cstmt.setInt(2, 6);

侃侃尔雅

应该是sql写的有问题.另外. DriverManager链接数据库的代码提到外面,写在静态代码块里或init方法里. 防止多次请求初始化多次链接.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java