JDBC如何防止SQL注入

来源:互联网 发布:互联网金融 知乎 编辑:程序博客网 时间:2024/05/18 00:07
package com.jtxx.finddata;
  
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; 
import com.jtxx.util.ConnectionFactory;
  
public class FindDataDaoImpl implementsFindDataDao {
    privateConnection conn = null;
    privatePreparedStatement ps = null;
    privateResultSet rs = null;
    privateStatement st = null;
//  public ZhiYuan findData1(String name,String card) {
//      String sql = "select a002,a008,a046 from gzjbk z where z.a002='"+name+"' and z.a008='"+card+"'";
//      try {
//          conn = ConnectionFactory.getConnection();
//          st = conn.createStatement();
//          
//          rs = st.executeQuery(sql);
//          if (rs.next()) {
//              ZhiYuan info = new ZhiYuan();
//              info.setName(rs.getString(1));
//              info.setCard(rs.getString(2));
//              info.setAmount(rs.getBigDecimal(3));
//              return info;
//          }
//          
//      } catch (Exception e) {
//          e.printStackTrace();
//      } finally{
//          closeAll(conn,ps,rs);
//      }
//      return null;
//  }
    publicZhiYuan findData(String name,String card) {
        String sql ="select a002,a008,a046 from gzjbk z where z.a002=? and z.a008=?";
        try{
            conn = ConnectionFactory.getConnection();
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
            ps.setString(2, card);
            rs = ps.executeQuery();
            if(rs.next()) {
                ZhiYuan info =new ZhiYuan();
                info.setName(rs.getString(1));
                info.setCard(rs.getString(2));
                info.setAmount(rs.getBigDecimal(3));
                returninfo;
            }
              
        }catch (Exception e) {
            e.printStackTrace();
        }finally{
            closeAll(conn,ps,rs);
        }
        returnnull;
    }
    publicstatic void closeAll(Connection conn,PreparedStatement ps,ResultSet rs){
        try{
            if(rs!=null)rs.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        try{
            if(ps!=null)ps.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        try{
            if(conn!=null)conn.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
原创粉丝点击