首页 > 代码库 > Java BaseDao
Java BaseDao
BaseDao类:
package dao;import java.sql.*;public class BaseDao { private static final String driver = "oracle.jdbc.driver.OracleDriver"; private static final String url = "jdbc:oracle:thin:@localhost:1521:ACCP"; private static final String uid = "scott"; private static final String pwd = "scott"; private static Connection con; private static PreparedStatement pstmt; /** * 建立连接对象 * @return */ public static Connection getConnection() { try { Class.forName(driver); con = DriverManager.getConnection(url, uid, pwd); return con; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; } /** * 关闭对象 * @param rs 数据集对象 */ public static void Close(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (con != null) { try { con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** * 执行查询操作 * @param sql 查询的sql语句 * @param paras 查询的参数 Object[]数组 * @return 结果集 */ public static ResultSet ExecuteQuery(String sql, Object[] paras) { getConnection(); try { pstmt = con.prepareStatement(sql); if (paras != null && paras.length > 0) { for (int i = 0; i < paras.length; i++) { pstmt.setObject(i + 1, paras[i]); } } ResultSet rs = pstmt.executeQuery(); return rs; } catch (SQLException e) { e.printStackTrace(); return null; } } /** * 执行增加、修改、删除操作 * @param sql 操作的sql语句 * @param paras 操作的参数 * @return 受影响的行数 */ public static int ExecuteUpdate(String sql, Object[] paras) { getConnection(); try { pstmt = con.prepareStatement(sql); if (paras != null && paras.length > 0) { for (int i = 0; i < paras.length; i++) { pstmt.setObject(i + 1, paras[i]); } } int rs = pstmt.executeUpdate(); return rs; } catch (SQLException e) { e.printStackTrace(); return -1; } }}
调用:
package dao;import java.sql.*;import java.util.ArrayList;import java.util.List;import entities.Emp;public class empDao { public List<Emp> GetEmpList() { ResultSet rs = BaseDao.ExecuteQuery("select * from emp", null); try { List<Emp> list = new ArrayList<Emp>(); while (rs.next()) { Emp e = new Emp(); e.setEmpno(rs.getInt("empno")); e.setEname(rs.getString("ename")); e.setJob(rs.getString("job")); e.setMgr(rs.getInt("mgr")); e.setHiredate(rs.getDate("hiredate")); e.setSal(rs.getDouble("sal")); e.setComm(rs.getDouble("comm")); e.setDeptno(rs.getInt("deptno")); list.add(e); } return list; } catch (SQLException e) { e.printStackTrace(); return null; } finally { BaseDao.Close(rs); } }}
Java BaseDao
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。