在代码徳开发过程中使用封装工具类,可以明显减少代码徳数量,避免代码冗余;
下面是我的一个例子:
使用简单的封装类:JDBCUtils
package com.alex.util;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class JDBCUtils {
static String driverClass;
static String url;
static String user;
static String password;
static {
try {
Properties properties = new Properties();
properties.load(new FileInputStream("resource/db.properties"));
//反射加载读取项目配置文件
//properties.load(JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties"));
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
user = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driverClass);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接
public static Connection getConnection() throws Exception{
Connection connection = DriverManager.getConnection(url, user, password);
return connection;
}
//关闭连接
public static void closeConnection(ResultSet resultSet,Statement statement,Connection connection) throws Exception{
if(resultSet != null){
resultSet.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
}
}
使用 :
package com.alex.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import org.junit.Test;
import com.alex.util.JDBCUtils;
public class TextConnection4 {
@Test
public void test01() throws Exception{
Connection connection = JDBCUtils.getConnection();
Statement statement = connection.createStatement();
String sql = "select * from admin";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
int id = resultSet.getInt(1);
System.out.println("id ->" + id);
}
JDBCUtils.closeConnection(resultSet, statement, connection);
}