获取和关闭连接 (经典)

来源:互联网 发布:图片相似度算法tensor 编辑:程序博客网 时间:2024/06/05 17:33

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.sun.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.sql.Statement;
/**
 *
 * @author Administrator
 */

public class ConnectionDB {
     private static final String DRIVER_CLASS = "com.microsoft.jdbc.sqlserver.SQLServerDriver";
     private static final String DATABASE_URL = "jdbc:microsoft:sqlserver://202.253.202.21:1433;DatabaseName=carPrj";
     private static final String DATABASE_USERS = "sa";
     private static final String DATABASE_PASSWORD = "sa";

     //获取连接
     public static Connection getConnection(){
          Connection connection = null;
          try {
               Class.forName(DRIVER_CLASS);
               connection = DriverManager.getConnection(DATABASE_URL,DATABASE_USERS,DATABASE_PASSWORD);
          } catch (ClassNotFoundException e) {
               e.printStackTrace();
          } catch (SQLException e) {
               e.printStackTrace();
          }
          return connection;
     }

     //关闭连接
     public static void closeConnection(Connection connection){
          try {
               if(connection != null && (!connection.isClosed())){
                    connection.close();
               }
          } catch (SQLException e) {
               e.printStackTrace();
          }
     }

     //关闭结果集
     public static void closeResultSet(ResultSet rs){
          try {
               if(rs != null) {
                    rs.close();

               }
          }catch (SQLException e) {
               e.printStackTrace();
          }
     }

     //关闭执行语句
     public static void closeStatement(PreparedStatement ps){
          if(ps != null){
               try {
                    ps.close();
                    ps = null;
               } catch (SQLException e) {
                    e.printStackTrace();
               }
          }
     }

     public static void closeStatement(Statement stmt) {
          if(stmt != null) {
               try {
                    stmt.close();
                    stmt = null;
               } catch (SQLException e) {
                    e.printStackTrace();
               }
          }
     }
}