JDBC学习记录——mysql报错:Parameter index out of range (1 > number of parameters, which is 0)

题目:在mysql数据库的scott表中使用子查询的方式查询哪些职员在XXX地工作。
java中的查询语句:

String sql = "select * from  emp where deptno = (select deptno from dept where loc = '?')";

遇到问题1:因为mysql的字符串用单引号,所以该不该用单引号处理此处的问号?
遇到问题2:主要问题,报错:Parameter index out of range (1 > number of parameters, which is 0)


mysql报错

以下为全部源代码

public static void main(String[] args) {
        try {
//          加载驱动
            Class.forName("com.mysql.jdbc.Driver");
//          连接数据库
            String url = "jdbc:mysql://localhost:3306/mysqldb";
            String username = "root";
            String password = "root";
            Connection con= DriverManager.getConnection(url,username,password);
//          输入语句
            Scanner sc = new Scanner(System.in);
            System.out.println("请输入条件1");
            String loc = sc.nextLine();
//          建立SQL对象
            String sql = "select * from  emp where deptno = (select deptno from dept where loc = '?')";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, loc);
//          结果集
            ResultSet rs = ps.executeQuery();
//          结果输出
            if(rs.next()) {
                int empno = rs.getInt("empno");
                String ename = rs.getString("ename");
                String job = rs.getString("job");
                int mgr = rs.getInt("mgr");
                Date hiredate = rs.getDate("hiredate");
                double sal = rs.getDouble("sal");
                double comm = rs.getDouble("comm");
                int deptno = rs.getInt("deptno");
                System.out.println("员工编号:"+empno+",员工姓名:"+ename+",职位:"+job+",领导编号:"+mgr+",入职日期:"+hiredate+",工资:"+sal+",奖金:"+comm+",部门编号:"+deptno);
                
            }
            rs.close();
            ps.close();
            con.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
    }

经过研究和网络大佬的答疑解惑,得出结论:
错误发生原因其实很简单,就是当设置参数时,没有相应的问号与之匹配
简单的说就是根本就没有问号。
例如:
如果是:

Parameter index out of range (26 > number of parameters, which is 25). 

翻译为:找到了25个问号,却插入了26个值,导致参数越界(根据得到的信息打印将很容易判断数据是否与数据库字段匹配等小问题)。

遇到问题3:第二种情况 like的用法
like模糊查询,like后跟单引号和@_进行模糊查询,搭配问号会让系统检测不到问号。
解决办法:

Scanner sc = new Scanner(System.in);
            System.out.println("请输入包含字母");
            String back = sc.nextLine();
            String something = "%" + back + "%";

            
            String sql = "select ename from emp where deptno in(select deptno from emp where ename in(select ename from emp where ename like ?))";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setString(1, something);

你可能感兴趣的:(JDBC学习记录——mysql报错:Parameter index out of range (1 > number of parameters, which is 0))