【问题标题】:I am getting this error java.sql.SQLException: Subquery returns more than 1 row我收到此错误 java.sql.SQLException:子查询返回超过 1 行
【发布时间】:2016-02-07 04:39:14
【问题描述】:

我有两个表 1.users 表(列:branch_id)和 2.branches 表(列:branch_id,branch_name)。

在我的表单中,我有一个分支字段,即选择字段。在该选择字段中,我需要从带有列分支名称的分支表中获取值。我做了那个功能。

现在我的要求是,在数据库中,我需要根据该 branch_name 在分支表中的用户表中插入 brach_id,

这是我的查询功能

 String query = "insert into users(full_name,gender,mobile_number,"
            + "email,password,department,designation,emp_code,branch_id,created_on,created_by,last_logged_on) "
            + "values(?,?,?,?,?,?,?,?,"
            + "(select id from branches where branch_name=?),?,?,?)";
    if(con!=null){
        try{
         ps=con.prepareStatement(query);
         ps.setString(1, bean.getName());
         if(bean.getGender().equals("Female")){
             ps.setInt(2,1);
         }else{
             ps.setInt(2,0);
         }
         ps.setString(3, bean.getMobile());
         ps.setString(4, bean.getUserid());
         ps.setString(5, bean.getPassword());
         ps.setString(6, bean.getDepartment());
         ps.setString(7, bean.getDesignation());
         ps.setString(8, bean.getEmpcode());
         ps.setInt(9, bean.getBranchId());
         ps.setTimestamp(10, new java.sql.Timestamp(new Date().getTime()));
         ps.setInt(11, bean.getCreatedBy());
         ps.setTimestamp(12, new java.sql.Timestamp(new Date().getTime()));
         insert_flag=ps.executeUpdate();

我认为查询工作正常。我在准备好的声明中遇到了一些错误,我不这么认为。

谁能帮帮我。

如果我像这样传递 brach_name

select id from branches where branch_name='"+branch+"'在选择查询中我收到此错误`java.sql.SQLException: Parameter index out of range (12 > number of parameters, which is 11).

请帮帮我

【问题讨论】:

    标签: java mysql


    【解决方案1】:

    此查询select id from branches where branch_name=? 为branch_name 的某个值返回多个结果。您的分支表中有重复的分支名称。

    【讨论】:

    • 如果我像这样通过分支(从 branch_name='"+branch+"' 的分支中选择 id),我在方法中传递的分支我收到此错误 java.sql.SQLException: Parameter index out范围(12 > 参数数量,即 11)。
    【解决方案2】:

    实际上,您在这里插入单行并尝试在 branch_id 列中插入多行,因此出现错误。只需将下面的插入语句更改为您的并尝试-

     String query = "insert into users(full_name,gender,mobile_number,"
                + "email,password,department,designation,emp_code,branch_id,created_on,created_by,last_logged_on) "
                + "values(?,?,?,?,?,?,?,?,"
                + "(select id from branches where branch_name=? limit 1),?,?,?)";
    

    【讨论】:

    • 我添加了你的代码,但它总是插入分支表的第一个 id,即 1。我想插入branch_name对应的id值。请帮助我它不工作。
    • 是的,正如我所说的,之前的问题是您尝试在单列中插入单行但多行值....如果您想要批量插入,则分别插入每一行或首先准备您的临时表中的数据,然后使用其他表中的插入数据....或者您可以准备一个 csv 文件,然后批量上传。
    猜你喜欢
    • 1970-01-01
    • 2011-12-13
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多