JDBC封装
首先创建db.properties文件
往db中添加
driver = com.mysql.jdbc.Driver
//连接本地地址的数据库,如修改多端口号,填写相应的端口号
url = jdbc:mysql://127.0.0.1(本地地址):3306(端口号)/java1ssm(数据库名称)?useSSL=true&characterEncoding=utf8
username = root//需要连接数据的账号
password = 123//需要连接数据库的密码
public class DBUtil {
// 解决维护性功能 properties
private static String driver ;
private static String url ;
private static String username ;
private static String password ;
//使用静态代码块
public Connection conn = null;
public PreparedStatement pstm = null;
public ResultSet rs = null;
public static Properties properties = new Properties();
// 获取db.properties资源 , static方法代表软件一打开就会自动加载资源文件
static {
try {
//读取资源文件 ,获取值
//创建properties集合类
properties.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties"));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
} catch (IOException e) {
e.printStackTrace();
}
}
// 1. 实现数据库连接的获取
public Connection getConn(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
// 2. 实现增删改的BaseDao封装
public int executeUpdate(String sql,Object[] params){ // Object[] 占位?不知道是什么数据类型,所有用了泛型处理
int num = 0;
try {
pstm = conn.prepareStatement(sql);
// 怎么处理占位符?
if(params!=null){
for(int i=0;i<params.length;i++){
pstm.setObject((i+1),params[i]);
}
}
num = pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
return num;
}
// 3. 实现查询的BaseDao封装
public ResultSet executeQuery(String sql,Object[] params){
ResultSet rs = null;
try {
pstm = conn.prepareStatement(sql);
// 怎么处理占位符?
if(params!=null){
for(int i=0;i<params.length;i++){
pstm.setObject((i+1),params[i]);
}
}
rs = pstm.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
return rs;
}
// 4. 实现数据库资源释放
public void closeResource(ResultSet rs, PreparedStatement pstm,Connection conn){
//要判空,不然会导致空指针异常
if(rs!=null){
try {
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(pstm!=null){
try {
pstm.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}