天天看點

JDBC連接配接的規範化代碼

資料庫連接配接在日常的項目中用的是比較多的,其文法也是比較簡單的,但是能夠很全面的規範化的寫出來也是不容易的。下面就簡單記下,以備日後複用:

package com.easyteam.yc;

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

/**
 * <p>title DaoUtils
 * <p>Description:mysql連接配接的規範化代碼 <P>
 * <P>Company:com.easyteam.cn
 * @author yc
 * @date 2016-6-28 下午05:10:37
 *
 */
public class DaoUtils {
	
		 static String DriverName="com.mysql.jdbc.Driver";
	     static String url="jdbc:mysql://localhost:3306/test";
		 static String username="root";
		 static String password="1";
		//靜态代碼塊,隻執行一次,因為隻需要加載一次就好,提高效率
	static{
		 
		 try {
			Class.forName(DriverName);
		} catch (ClassNotFoundException e) {
			 throw new RuntimeException(e);
		}
	}
	public static Connection getConnection(){
			Connection con=null;
			PreparedStatement psmt=null;
			ResultSet rs=null;
		try {
			con=DriverManager.getConnection(url, username, password);
			return con;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}finally{
			if(rs!=null)//這個地方是是以要判斷循環,就是上面有可能有異常,那麼不判斷可能就會出現空指針異常
				try {
					rs.close();
				} catch (SQLException e) {
				throw new RuntimeException(e);
				}
				if(psmt!=null)
				 try {
						psmt.close();
					} catch (SQLException e) {
				throw new RuntimeException(e);
					}
					if(con!=null)
						try {
							con.close();
						} catch (SQLException e) {
				throw new RuntimeException(e);
				}
			
		}
		
	}
		
	
}
           

測試代碼:

ackage com.easyteam.yc;

import java.sql.Connection;

import org.junit.Test;

/**
 * <p>title Test
 * <p>Description:測試使用 <P>
 * <P>Company:com.easyteam.cn
 * @author yc
 * @date 2016-6-28 下午05:38:41
 *
 */
public class TestDemo {
	@Test
	public  void fun(){
		DaoUtils du=new DaoUtils();
		Connection con=du.getConnection();
		System.out.println(con);
	}
}