package com.bdqn.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
final String DRIVERNAME = "com.mysql.jdbc.Driver";
final String URL = "jdbc:mysql://localhost:3306/myschool";
final String USER = "root";
final String PASSWORD = "admin123";
//私有的数据库连接
private Connection connection;
private PreparedStatement pstmt;
public Connection getConnection() {
try {
//加载驱动
Class.forName(DRIVERNAME);
//如果存在,则直接返回,如果不存在,则直接创建再返回
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* 关闭所有数据库连接
*/
public void closeAll(ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) {
try {
pstmt.close();
System.out.println("关闭PreparedStatement");
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
System.out.println("关闭数据库连接");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
/**
* 增删改方法
* @param sql
* @param obj
* @return
*/
public int executeUpdate(String sql,Object ... obj){
//1:获取数据库连接
Connection conn = getConnection();
//2:获取PreparedStatement对象
int num = -1;
try {
//2:
pstmt = conn.prepareStatement(sql);
//3:填入参数
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(i+1, obj[i]);
}
//4:执行sql语句
num = pstmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll(null);
}
return num;
}
/**
* 查询方法,特点,使用完这个方法,记得调用closeAll关闭ResultSet
* @param sql sql语句
* @param obj 可变参数
* @return
*/
public ResultSet executeQuery(String sql,Object ... obj){
//1:获取数据库连接
Connection conn = getConnection();
//2:获取PreparedStatement对象
ResultSet rs = null;
try {
pstmt = conn.prepareStatement(sql);
//3:填入参数
for (int i = 0; i < obj.length; i++) {
pstmt.setObject(1, obj[i]);
}
//4:执行sql语句
rs = pstmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}