首页 > 代码库 > 封装连接数据库

封装连接数据库

package com.huawei.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
* @author Administrator
*
*/
public class DBUtil {


/**
* 得到数据库连接
* @return
*/
public static Connection getConnection(){
//显示加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");
return connection;
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return null;
}

/**
*
* 释放资源
* @param objects
*/
public static void close(Object ...objects){
if(objects!=null && objects.length>0){
try {
for(Object o:objects){
if(o instanceof ResultSet){
((ResultSet)o).close();
}else if(o instanceof Statement){
((Statement)o).close();
}else if(o instanceof Connection){
((Connection)o).close();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

封装连接数据库