import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class BaseDao { private static final String DRIVER="oracle.jdbc.driver.OracleDriver"; private static final String URL="jdbc:oracle:thin://@localhost:1521:orcl"; private static final String USER="scott"; private static final String PASSWORD="root"; /** * 结果集 */ protected ResultSet rs; /** * 预处理SQL对象 */ protected PreparedStatement ps; /** * 连接对象 */ protected Connection conn; protected Connection getConn(){ Connection conn=null; try { Class.forName(DRIVER); conn=DriverManager.getConnection( URL, USER, PASSWORD); } catch (ClassNotFoundException | SQLException e) { e.printStackTrace(); } return conn; } /** * * @param rs * @param ps * @param conn * 作者 :dis.jiang */ protected void closeAll(){ try { if(rs!=null){ rs.close(); rs=null; } if(ps!=null){ ps.close(); ps=null; } if(conn!=null){ conn.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //===========================通用的SQL操作============================== /** * 通用删除,修改,添加 * @param sql * @param params * @return * 作者 :dis.jiang */ public int execute(String sql,Object...params){ int num=0; conn = getConn(); try { ps=conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1, params[i]); } num= ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally{ closeAll(); } return num; } /** * 通用查询 * @param sql * @return * 作者 :dis.jiang */ public ResultSet select(String sql,Object...params){ conn = getConn(); try { ps = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { ps.setObject(i+1, params[i]); } rs=ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } }
原文地址:https://www.cnblogs.com/jiangaihu/p/10955798.html
时间: 2024-10-08 11:38:23