Java and SQL : return null or throw exception?

前端 未结 6 995
面向向阳花
面向向阳花 2021-01-21 10:09

This is another debated subject, but this time i am searching only for the simple and documented answers. The scenario :

Let\'s assume the following method:



        
6条回答
  •  旧巷少年郎
    2021-01-21 10:37

    You can significantly reduce the amount of boilerplate JDBC code by using Spring-JDBC instead of plain-old JDBC. Here's the same method rewritten using Spring-JDBC

    public static Hashtable getSomeDogs(String colName, String colValue) {
    
        StringBuffer sql = new StringBuffer();
        sql.append("SELECT * FROM ").append("dogs_table");
        sql.append(" WHERE ").append(colName).append("='");
        sql.append(colValue).append("'");
    
        Hashtable result = new Hashtable();
    
        RowMapper mapper = new RowMapper() {
    
            public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                Dogs dog = new Dogs();
                //...initialize the dog from the current resultSet row
                result.put(new Long(dog.getId()), dog);
            }
        };
        (Hashtable) jdbcTemplate.queryForObject(sql, mapper);
    }
    

    Spring takes care of:

    1. Iterating over the ResultSet
    2. Closing the ResultSet
    3. Handling exceptions consistently

    As others have mentioned you really should use a PreparedStatement to construct the SQL instead of a String (or StringBuffer). If for some reason you can't do this, you could improve the readability of the query by constructing the SQL like this instead:

        String sql = 
            "SELECT * FROM dogs_table " +
            "WHERE " + "colName" + " = '" + colValue + "'";
    

提交回复
热议问题