java关闭mysql数据库_java mysql数据库链接与资源关闭

/*** Created by Clear on 2018/8/11.

* here provide the kind of connections from mysql database,and close the resources of the mysql

* there are

* load driver

* use properties file

* use xml file

* use tomcat

* and... so on

*

*

**/

public classMysqlUtil {/*** 链接数据库*/

/*** 方法一:

* 加载驱动的方法不止一种,但这种最常用*/

public staticConnection getConnectionOne(String database,String username,String password){try{

Class.forName("com.mysql.jdbc.Driver");

Connection connection= DriverManager.getConnection("jdbc:mysql://localhost:3306/"+database,username,

password);returnconnection;

}catch(Exception e){

e.printStackTrace();

}return null;

}/*** 方法二:

* 利用properties文件

* ::::: 在Web 编程时 文件难以定位*/

public staticConnection getConnectionTwo() {/*** 建立文件*/Properties pro= newProperties();

InputStream in= MysqlUtil.class.getClassLoader().getResourceAsStream("mysqllog.properties");try{

pro.load(in);

Class.forName(pro.getProperty("driver"));

String username= pro.getProperty("user");

String password= pro.getProperty("password");

String database= pro.getProperty("database");

String url= pro.getProperty("url");

Connection connection= DriverManager.getConnection(url+database,username,password);returnconnection;

}catch(Exception e) {

e.printStackTrace();

}return null;

}//Connection ,Statement, ResultSet 这几个资源的关闭是有顺序的

public static void close (Object...objects) throwsMysqlCloseException {

Map map = newHashMap();for(Object o : objects){if(o instanceofResultSet){

map.put("ResultSet",o);

}else if(o instanceofConnection){

map.put("Connection",o);

}else if(o instanceofStatement){

map.put("Statement",o);

}else if(o instanceofPreparedStatement){

map.put("PreparedStatement",o);

}else{throw new MysqlCloseException("关闭异常,不能处理");

}

}

Object obj= map.get("ResultSet");if(obj!=null){

ResultSet r=(ResultSet)obj;try{

r.close();

map.remove("ResultSet");

}catch(SQLException e) {

e.printStackTrace();

}

}

obj= map.get("PreparedStatement");if(obj!=null){

PreparedStatement p=(PreparedStatement)obj;try{

p.close();

map.remove("PreparedStatement");

}catch(SQLException e) {

e.printStackTrace();

}

}

obj= map.get("Statement");if(obj!=null){

Statement s=(Statement)obj;try{

s.close();

map.remove("Statement");

}catch(SQLException e) {

e.printStackTrace();

}

}

obj= map.get("Connection");if(obj!=null){

Connection c=(Connection)obj;try{

c.close();

map.remove("Connection");

}catch(SQLException e){

e.printStackTrace();

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值