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

jdbc工具类
package com.jdbctest.Util;

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

public class JDBCUtil {
	
	//使用静态代码块
	static{
		try {    //加载数据库驱动
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//连接数据库参数
	private static final String URL="jdbc:mysql://127.0.0.1:3306/test";
         private static final String USER="root";
	private static final String PASSWORD="******";
	
	/**
	 * 获取数据库连接对象
	 * @return Connection
	 * @throws SQLException
	 */
	public static Connection getConnection(){
		//return DriverManager.getConnection(URL, USER, PASSWORD);throws SQLException
		Connection conn = null;
		try {
			conn=DriverManager.getConnection(URL,USER,PASSWORD);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}
	
	/**
	 * 关闭已经打开的
	 * @param rs ResultSet 数据库结果对象
	 * @param stmt Statement 数据库操作对象
	 * @param conn Connection 数据库连接对象
	 */
	public static void close(ResultSet rs,Statement stmt,Connection conn){
			try {
				if(rs!=null) rs.close();
				if(stmt!= null) stmt.clearBatch();
				if(conn!=null) conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		
	}
}