JDBC连接的封装函数

import java.sql.*;
//封装数据库操作相关函数
public class DB {
	//拿到Connection
	public static Connection getConnection(){
		Connection conn = null;
		try {
			Class.forName("com.mysql.jdbc.Driver");
			 conn = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=****");
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
		
	}
	//拿到Statement
	public static Statement getStatement(Connection conn){
		Statement sttm = null;
		try {
			sttm = conn.createStatement();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return sttm;
		
	}
	//拿到ResultSet
	public static ResultSet getResultSet(Statement sttm,String sql){
		ResultSet rs = null;
		try {
			rs = sttm.executeQuery(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return rs;
		
	}
	//关闭相关的连接
	public static void close(Connection conn){
		
			try {
				if(conn != null){
					conn.close();
					conn = null;
				}
			} catch (SQLException e) {
				e.printStackTrace();
				System.out.println("关闭失败");
			}
			
		
	}
	public static void close(Statement sttm){
		try{
			if(sttm != null){
				sttm.close();
				sttm = null;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	public static void close(ResultSet rs){
		try{
			if(rs != null){
				rs.close();
				rs = null;
			}
		}catch(SQLException e){
			e.printStackTrace();
		}
	}

}

你可能感兴趣的:(JDBC)