JDBC工具类和配置文件

JDBC是java中为了和数据库进行交流而开发的一套数据库规范,以下工具类用于灵活的产生数据库连接和安全的释放数据库连接

程序使用的Mysql,但对于其他的数据库只需要改变配置文件即可使用

JDBCFactory.java

package com.jdbc.jdbc;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;


public class JDBCFactory {
	//定义连接数据库所需要的字段
	private static String driveClassName = null;
	private static String url = null;
	private static String username = null;
	private static String password = null;
	//通过配置文件为以上字段赋值
	static{
		try {
			InputStream in = JDBCFactory.class.getClassLoader().getResourceAsStream("dbcfg.properties");
			Properties prop = new Properties();
			prop.load(in);
			driveClassName = prop.getProperty("className");
			url = prop.getProperty("url");
			username = prop.getProperty("username");
			password = prop.getProperty("password");
			//加载驱动类
			Class.forName(driveClassName);
		} catch (Exception e) {
			throw new RuntimeException("Can't find the properties!");
		}
	}
	//得到连接
	public static Connection getConnection() throws SQLException {
		return DriverManager.getConnection(url,username,password);
	}
	//释放资源
	public static void release(ResultSet rs,Statement stmt,Connection conn) {
		if(rs != null) {
			try{
				rs.close();
			}catch(Exception e){} //ignore
			rs = null;
		}
		if(stmt != null) {
			try{
				stmt.close();
			}catch(Exception e){} //ignore
			stmt = null;
		}
		if(conn != null) {
			try {
				conn.close();
			}catch(Exception e){} //ignore
		}
		
	}
	
}

dbcfg.properties

className=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/[数据库名称]?userUnicode=true&characterEncoding=utf-8
username=[数据库用户名]
password=[数据库密码]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值