【问题标题】:Error with delete statement in jdbcTemplatejdbcTemplate 中的删除语句出错
【发布时间】:2017-05-20 04:00:15
【问题描述】:

为了找出错误,我做了很多搜索工作。我发现许多其他学习者也有同样的错误,但它是针对插入语句的。但是我的问题似乎是在寻找删除语句的问题。我收到以下错误:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL [delete from tbl_cust where Cust_id=2]; Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).

但是,当我在 localhost/phpmyadmin/ 中查询相同的 sql 时,它会删除记录而没有错误 我尝试了以下一些方法:

public int delete(int id) throws ClassNotFoundException, SQLException {
    String sql= "DELETE FROM tbl_cust WHERE Cust="+id;
    Object[] obj={id};
    return JdbcTemplate.update(sql,obj);
}

这是下一个例子

 public int delete(int id) throws ClassNotFoundException, SQLException {
    String sql= "DELETE FROM tbl_cust WHERE Cust_id=?";
    Object[] obj={id};
    return JdbcTemplate.update(sql,obj);
}

【问题讨论】:

    标签: java mysql spring-mvc jdbctemplate


    【解决方案1】:

    使用 getSimpleJdbcTemplate() 代替 JdbcTemplate

    public void deleterecord(int hostId)
    {
    String sql= "DELETE FROM tbl_cust WHERE Cust_id=?";
    getSimpleJdbcTemplate().update(sql, hostId);
    }
    

    【讨论】:

      【解决方案2】:

      使用 JdbcTemplate 中的更新方法。将 jdbcTemplate.update(sql,obj) 行替换为 jdbcTemplate.update(sql,id)

      另外,仅供参考,更新会执行以下所有操作:

      1. 更新
      2. 删除
      3. 插入

      【讨论】:

      • 您能否复制错误或打印堆栈跟踪,以便我们详细了解实际情况。还请提供您认为解决此错误所需的任何进一步详细信息。
      • 我通过添加我遇到的错误来编辑我的问题
      • 如果您使用语句 “DELETE FROM tbl_cust WHERE Cust_id=?”,显然它应该可以工作。现在您可能需要调试并查看该语句是否在其参数中保存了预期值。
      • 调试成功了吗?
      • 幸好成功了
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2020-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      相关资源
      最近更新 更多