/**
* 数据库访问类
*/
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();
}
}
}