javaweb 连接数据库使用封装工具类

在代码徳开发过程中使用封装工具类,可以明显减少代码徳数量,避免代码冗余;
下面是我的一个例子:

使用简单的封装类: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);
	}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值