日期:2014-05-16  浏览次数:20557 次

JDBC 建立连接公共操作类(静态方式与单例方式)

静态方式

package com.ighost.jdbc;

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

/**
 * 
 * 数据库操作公共类
 * 
 * @author ghost
 * 
 */
public final class JDBCUtil {

 private static String url = "jdbc:mysql://localhost:3306/jdbc";

 private static String username = "root";

 private static String password = "";

 // 构造函数私有话 不允许构造
 private JDBCUtil() {
 }

 // 注册驱动
 static {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   throw new ExceptionInInitializerError(e);
  }
 }

 // 获取连接
 public static Connection getConnection() throws SQLException {
  return DriverManager.getConnection(url, username, password);
 }

 // 释放资源
 public static void free(ResultSet rs, Statement stmt, Connection conn) {
  try {
   if (rs != null) {
    rs.close();
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    if (stmt != null) {
     stmt.close();
    }
   } catch (SQLException e) {
    e.printStackTrace();
   } finally {
    try {
     if (conn != null) {
      conn.close();
     }
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
 }
}
单例方式

package com.ighost.jdbc;

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

/**
 * 
 * 数据库操作公共类 单例模式 虚拟机里只存在一个这样的实例 通过getInstance方式获取对象
 * 
 * @author ghost
 * 
 */
public final class JDBCUtilSingle {

 private String url = "jdbc:mysql://localhost:3306/jdbc";

 private String username = "root";

 private String password = "";

 // 构造函数私有话 不允许构造
 private JDBCUtilSingle() {
 }

 // 构造私有实例
 // private static JDBCUtilSingle instance = new JDBCUtilSingle();
 private static JDBCUtilSingle instance = null;

 public static JDBCUtilSingle getInstance() {
  //延迟加载  
  if (instance == null) {
   //加锁 防止线程并发
   synchronized (JDBCUtilSingle.class) {
    //必须有的判断
    if(instance == null){
     instance = new JDBCUtilSingle(); 
    }     
   }   
  }
  return instance;
 }

 // 注册驱动
 static {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   throw new ExceptionInInitializerError(e);
  }
 }

 // 获取连接
 public Connection getConnection() throws SQLException {
  return DriverManager.getConnection(instance.url, instance.username,
    instance.password);
 }

 // 释放资源
 public static void free(ResultSet rs, Statement stmt, Connection conn) {
  try {
   if (rs != null) {
    rs.close();
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    if (stmt != null) {
     stmt.close();
    }
   } catch (SQLException e) {
    e.printStackTrace();
   } finally {
    try {
     if (conn != null) {
      conn.close();
     }
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
 }
}
?