2

我收到以下错误,但我不明白为什么:

org.springframework.jdbc.BadSqlGrammarException: PreparedStatementCallback; 错误的 SQL 语法 [UPDATE da_tracking SET ins_name= xyz, ins_dev_scripted = False WHERE ins_ID = 12]; 嵌套异常是 java.sql.SQLException: Invalid parameter index 1。

------------------------ dao class-----
public int save(DboBean record) {
        // TODO Auto-generated method stub
        String sql = "UPDATE da_tracking"
                    + " SET ins_name= " + record.getDboDevName()+ "," 
                    + " ins_dev_scripted = " + record.getDevScripted()
                    + " WHERE ins_ID = " + record.getDboId();
        Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted()};
        int[] types = new int[]{Types.VARCHAR, Types.BIT};
        return jdbcTemplate.update(sql, params, types);
    }
----------------------------Junit-----
bean.setDboDevName("xyz");
bean.setDboId(12);
int rowsAffected =  objDao.save(bean);

    System.out.println("Object is updated [" + bean.getDboId() + ", " + bean.getDboDevName() + 
            ", " + bean.getDevScripted() + "]");

你知道为什么吗??我的删除和读取方法有效。

4

2 回答 2

4

您看到的错误是因为您将变量传递给paramsandtypes数组,但您没有在查询中为这些绑定变量放置占位符:

String sql = "UPDATE da_tracking"
            + " SET ins_name= ?," 
            + " ins_dev_scripted = ?"
            + " WHERE ins_ID = ?"
Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted(), record.getDboId()};
int[] types = new int[]{Types.VARCHAR, Types.BIT, Types.INTEGER};
return jdbcTemplate.update(sql, params, types);

在内部,Spring 正在做这样的事情:

PreparedStatement stmt = conn.prepareStatement("...your sql...");
stmt.setString(1, dboDevName); // this will fail, since there is no bind variable
                               // with index 1
...

您永远不应该通过连接外部数据来构建 SQL 查询。在最好的情况下,如果有人在数据中加入奇怪的引号或转义字符,它会导致查询随机失败,在最坏的情况下,会导致一个重大的安全漏洞,从而危及您的系统。

于 2012-08-29T15:42:06.500 回答
1
public int save(DboBean record) {

        String sql = "UPDATE da_tracking"
                    + " SET ins_name= ?"+"," 
                    + " ins_dev_scripted = ?" 
                    + " WHERE ins_ID = ?";
        Object[] params = new Object[] {record.getDboDevName(), record.getDevScripted(), record.getDboId()};
        int[] types = new int[]{Types.VARCHAR, Types.BIT, Types.INTEGER}; // Change 3rd parameter type here
        return jdbcTemplate.update(sql, params, types);
    }

----------------------------Junit-----
bean.setDboDevName("xyz");
bean.setDboId(12);
int rowsAffected =  objDao.save(bean);

    System.out.println("Object is updated [" + bean.getDboId() + ", " + bean.getDboDevName() + 
            ", " + bean.getDevScripted() + "]");

这行得通吗?

于 2012-08-29T15:36:21.370 回答