BaseDao

/**
 * 数据库访问类
 */

public class BaseDao {

	//数据库驱动
	private static String driver = "com.mysql.jdbc.Driver";
	//数据库连接地址
	private static String url = "jdbc:mysql://127.0.0.1/flight?useSSL=False";
	//数据库用户名
	private static String user = "root";
	//数据库密码
	private static String password = "root";
	//连接数据库
	protected Connection conn = null;
	//statement对象
	protected PreparedStatement pstmt = null; 
	/**
	 * 连接数据库
	 */
	protected Connection getConn () throws ClassNotFoundException,SQLException{
		Class.forName(driver);
		conn = DriverManager.getConnection(url,user,password);
		return conn;
	}
	/**+
	 * 查询库方法
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	protected ResultSet executeQuerySQL(String sql, Object[] params) throws SQLException {
		ResultSet rs = null;
		try{
			conn = getConn();
		}catch ( ClassNotFoundException e){
			e.printStackTrace();
		}
		pstmt = conn.prepareStatement(sql);
		if(params != null){
			for( int i = 0 ; i < params.length ; i++){
				pstmt.setObject(i+1, params[i]);
			}
		}
		rs = pstmt.executeQuery();
		return rs;
	}	
	/**
	 * 数据库增删改方法
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	protected int executeUpdate(String sql,Object[] params) throws SQLException{
		try{
			conn = getConn();
		}catch ( ClassNotFoundException e){
			e.printStackTrace();
		}
		int num = 0;
		pstmt = conn.prepareStatement(sql);
		if(params != null){
			for( int i = 0 ; i < params.length ; i++){
				pstmt.setObject(i+1, params[i]);
			}
		}
		num = pstmt.executeUpdate();
		return num;
	}
	
	/**
	 * 关闭数据库
	 * @param conn
	 * @param pstmt
	 * @param rs
	 */
	protected void closeAll(Connection conn , PreparedStatement pstmt , ResultSet rs){
		try {
			if(rs != null)
				rs.close();
			if(pstmt != null)
				pstmt.close();
			if(conn != null)
				conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}	
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值