Java and SQL : return null or throw exception?

前端 未结 6 994
面向向阳花
面向向阳花 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:24

    Do not build SQL queries by concatenating strings, like you're doing:

    sql = new StringBuffer();
    sql.append("SELECT * FROM ").append("dogs_table");
    sql.append(" WHERE ").append(colName).append("='");
    sql.append(colValue).append("'");
    

    This makes your code vulnerable to a well-known security attack, SQL injection. Instead of doing this, use a PreparedStatement and set the parameters by calling the appropriate set...() methods on it. Note, you can only use this to set column values, you can't use this to dynamically construct a column name, as you're doing. Example:

    PreparedStatement ps = connection.prepareStatement("SELECT * FROM dogs_table WHERE MYCOL=?");
    ps.setString(1, colValue);
    
    rs = ps.executeQuery();
    

    If you use a PreparedStatement, the JDBC driver will automatically take care of escaping certain characters that might be present in colValue, so that SQL injection attacks don't work anymore.

提交回复
热议问题