首页 > 代码库 > BaseDAO,要背过哦
BaseDAO,要背过哦
package com.equipmentmanager.dao;
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 = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 链接的URL private static final String URL = "jdbc:sqlserver://localhost:1433;DatabaseName=equipmentDB"; // 登录sqlserver用户名密码 private static final String USERNAME = "sa"; private static final String PWD = "1234"; // 数据库对象声明 private Connection con = null; private PreparedStatement pst = null; private ResultSet rs = null; /** * 加载驱动,建立连接 * * @throws ClassNotFoundException * @throws SQLException */ private void getConnection() throws ClassNotFoundException, SQLException { Class.forName(DRIVER); con = DriverManager.getConnection(URL, USERNAME, PWD); }
/** * 执行更改(增加,删除,修改)SQL的方法 * * @param sql * 要执行的参数化的sql语句 * @param params * Object 数据,封装所有SQL语句参数,顺序与SQL语句参数顺序一致 * @return int型 受影响的行数 -1出现异常 */ public int execUpdate(String sql, Object[] params) { try { getConnection(); pst = con.prepareStatement(sql); setPrepareStatementParams(params); int affectedRows = pst.executeUpdate(); return affectedRows; } catch (ClassNotFoundException e) {
e.printStackTrace(); } catch (SQLException e) {
e.printStackTrace(); } finally { clossAll(); } return -1; }
/** * 执行查询 * * @param sql * 要执行的参数化的sql语句 * @param params * Object 数据,封装所有SQL语句参数,顺序与SQL语句参数顺序一致 * @return ResultSet 返回执行后的结果 结果集 */ public ResultSet execQuery(String sql, Object[] params) { try { // 获得连接 getConnection(); // 构造 pst = con.prepareStatement(sql); // 设置参数 setPrepareStatementParams(params);
rs = pst.executeQuery(); } catch (SQLException e) {
e.printStackTrace(); } catch (ClassNotFoundException e) {
e.printStackTrace(); } return rs; }
/** * 为PrepareStatement设置参数 * * @param params * 参数数组 * @throws SQLException */ private void setPrepareStatementParams(Object[] params) throws SQLException { if (params != null) { for (int i = 0; i < params.length; i++) { pst.setObject(i + 1, params[i]); } } }
/** * 关闭Connection,PrepareStatement,ResultSet */ public void clossAll() { try { if (rs != null) { rs.close(); } if (pst != null) { pst.close(); } if (con != null) { con.close(); } } catch (SQLException e) { e.printStackTrace();
} }
}
BaseDAO,要背过哦