jdbc的简单封装
jdbc.properties文件代码如下:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jdbc_db?useUnicode=true&characterEncoding=utf-8
username=root
password=1234
一、对连接的封装
//对jdbc的重用性代码进行封装
//=================连接和关闭====================
public class DbUtils2 {
//获取连接
private static Properties properties = new Properties();
static {
try{
//通过类自带的资源加载器加载文件资源
//========jdbc.properties放在同src同目录下========
//对于/jdbc.properties路径一定要正确
InputStream is = DbUtils2.class.getResourceAsStream("/jdbc.properties");
//创建Properties 属于Map集合的分支,可以键值对
Properties properties = new Properties();
//load方法
properties.load(is);
//只加载一次
Class.forName(properties.getProperty("driver"));
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(
properties.getProperty("url"),
properties.getProperty("username"),
properties.getProperty("password")
);
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
二、对关闭资源的封装
//关闭连接
//=======遵循先开后关原则===========
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
try {
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
三、测试
package com.itheima.utils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class TestJdbc {
@Test
public void testSelect() throws Exception {
Connection connection = DbUtils.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("select * from student;");
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
System.out.println(resultSet.getInt(1));
System.out.println(resultSet.getString(2));
System.out.println(resultSet.getInt(3));
System.out.println(resultSet.getString(4));
}
DbUtils.closeAll(connection,preparedStatement,resultSet);
}
}