获取驱动,连接数据库,关闭资源

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

public class DBUtil {
	   //初始化数据库四个准备条件
       private static final String DRIVER_CLASS = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
       private static final String URL = "jdbc:sqlserver://localhost:1433;databaseName=epet";
       private static final String USERNAME = "sa";
       private static final String PASSWORD = "sa";
       //创建数据库的驱动
       static {
    	   try {
			Class.forName(DRIVER_CLASS);
			System.out.print("获取驱动成功!");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	   
       }
       
       //创建连接数据库
       public static Connection getConnection() throws SQLException{
    	   //Connection conn = DriverManager.getConnection(URL,USERNAME,PASSWORD);
    	   //return conn;
    	   return DriverManager.getConnection(URL,USERNAME,PASSWORD);
       }
       //关闭资源,释放资源
       public static void closeAll(Connection conn ,Statement stmt,ResultSet rst) {
   		if(rst!=null) {
   			try {
   				rst.close();
   			} catch (SQLException e) {
   				// TODO Auto-generated catch block
   				e.printStackTrace();
   			}
   		}
   		if(stmt!=null) {
   			try {
   				stmt.close();
   			} catch (SQLException e) {
   				// TODO Auto-generated catch block
   				e.printStackTrace();
   			}
   		}
   		if(conn!=null) {
   			try {
   				conn.close();
   			} catch (SQLException e) {
   				// TODO Auto-generated catch block
   				e.printStackTrace();
   			}
   		}
   	}
}

 

你可能感兴趣的:(获取驱动,连接数据库,关闭资源)