JDBC--PreparedStatement使用

1、 PreparedStatement是Statement的子接口,可以传入传入带有占位符的SQL语句,并且提供了相应的方法来替换占位符(setXxx(int index, Object value)index从1开始),

然后通过executeUpdate或executeQuery()方法来执行SQL语句。

2、更新操作

public int update(String sql, Object ... args){
    int rowNum = 0;
    Connection conn = null;
    PreparedStatement ps = null;
    
    try{
        conn = getConnection();
        ps = conn.prepareStatement(sql);
        for(int i = 0; i < args.length; i++){
            ps.setObject(i + 1, args[i]);
        }
        
        rowNum = ps.executeUpdate();
        return rowNum;
    }catch(Exception e){
        e.printStackTrace();
    }finally{
        if(ps != null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    return rowNum;
}

3、查询操作

public static void query(){
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    
    StringBuffer sb = new StringBuffer("SELECT name, email, salary from emp1 ");
    sb.append("where id = ?");
    try{
        conn = getConnection();
        ps = conn.prepareStatement(sb.toString());
        
        ps.setInt(1, 1234);
        
            rs = ps.executeQuery();            

    if(rs.next()){ String name = rs.getString(1); String email = rs.getString(2); double salary = rs.getDouble(3); System.out.println(name + ":" + email + ":" + salary); } }catch(Exception e){ e.printStackTrace(); }finally{ if(rs != null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps != null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(conn != null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

4、SQL注入攻击:是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入中注入非法的SQL语句段或命令,从而利用系统的SQL引擎完成恶意行为的做法。

5、使用PreparedStatement可以有效地避免SQL注入。而Statement无法禁止SQL注入;

6、使用PreparedStatement可提高代码的可读性和可维护性,同时它能最大可能提高性能。

原文地址:https://www.cnblogs.com/tengtao93/p/4967151.html