初学JDBC,防SQL注入简单示例

时间:2023-01-09 13:39:24

在JDBC简单封装的基础上实现

public class UserDao{

  public static void testGetUser(String userName) throws Exception{

    Connection conn=null;

    PreparedStatement preparedStatement=null;//Statement换为PreparedStatement

    ResultSet resultSet=null;

    try{

      conn=JdbcUtils.getConnetcion();

      //查询语句参数化,防止SQL注入

      String sql="select * from user where userName=?";

      preparedStatement=conn.prepareStatement(sql);

      preparedStatement.setString(1,userName);

      resultSet=preparedStatement.excuteQuery();

      while(resultSet.next()){

        System.out.println(resultSet.getObject(1)+"\t"+resultSet.getObject(2));

      }

    }finally{

      JdbcUtils.freeResource(resultSet,preparedStatement,conn);

    }

  }

}