(26)数据库工具类DbUtil

package com.xuan.util;

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

public  abstract class DbUtil {
		static{
			try{
				System.out.println("注册数据库驱动....");
				Class.forName("com.mysql.jdbc.Driver");
				System.out.println("注册数据库驱动成功...");
			}catch(ClassNotFoundException e){
				throw new RuntimeException("注册数据库驱动出现异常:"+e.getMessage());
			}
			catch(Exception e2){
				e2.printStackTrace();
			}
			
		}
		
		public static Connection getConn(){
			String url="jdbc:mysql://localhost:3306/blog?characterEncoding=GBK";
				try{
					return DriverManager.getConnection(url,"root","root");
				}catch(SQLException e){
					throw new RuntimeException("无法获取连接,原因:"+e.getMessage());
				}
		}
		
		public static Statement getStatement(Connection conn){
				Statement stmt=null;
			try{
				if(conn!=null){
					stmt=conn.createStatement();
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
			return stmt;
		}
		
		public static PreparedStatement getPreparedStatement(Connection conn,String sql){
			PreparedStatement ps=null;
			try{
				if(conn!=null){
					ps=conn.prepareStatement(sql);
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
			return ps;
		}
		public static ResultSet getResultSet(Statement stmt,String sql){
					ResultSet rs=null;
					try{
						if(stmt!=null){
							rs=stmt.executeQuery(sql);
						}
					}catch(SQLException e){
						e.printStackTrace();
					}
					return rs;
		}
		
		public static void closeConn(Connection conn){
			try{
				if(conn!=null){
					conn.close();
					conn=null;
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		public static void closeStmt(Statement stmt){
			try{
				if(stmt!=null){
					stmt.close();
					stmt=null;
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		public static void closeRs(ResultSet rs){
			try{
				if(rs!=null){
					rs.close();
					rs=null;
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
		public static void closePs(PreparedStatement ps){
			try{
				if(ps!=null){
					ps.close();
				}
			}catch(SQLException e){
				e.printStackTrace();
			}
		}
		
}

你可能感兴趣的:((26)数据库工具类DbUtil)