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

JDBC首选工具类

在用JDBC连接数据库时可以先写一个工具类以达到方便的效果:

package com.sun.java.utils;

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

/**
 * @author Dell JDBC工具类
 */
public class JDBCUtils {

 private static String url = "jdbc:mysql://localhost:3306/thr";
 private static String user = "root";
 private static String password = "1";

 // 静态代码块加载驱动
 static {
  try {
   Class.forName("com.mysql.jdbc.Driver");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

 // 获取连接的方法
 public static Connection getConnection() throws SQLException {
  return DriverManager.getConnection(url, user, password);

 }

 // 释放资源的方法
 public static void free(ResultSet rs, PreparedStatement ps, Connection cn) {
  try {
   if (rs != null) {
    rs.close();
   }
  } catch (Exception e) {
   // TODO: handle exception
  } finally {
   try {
    if (ps != null) {
     ps.close();
    }
   } catch (Exception e2) {
    // TODO: handle exception
   } finally {
    if (cn != null) {
     try {
      cn.close();
     } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    }
   }
  }
 }
}