编写连接数据库的工具类

package cn.itcast.jdbc;

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

import com.mysql.jdbc.Statement;

//将驱动注册优化掉
public final class JdbcUtils {
	private static String url = "jdbc:mysql://localhost:3306/jdbc";
	private static String user = "root";
	private static String password = "123";
	private JdbcUtils(){
		
	}
	static{
		try{                                 //注册驱动
			Class.forName("com.mysql.jdbc.Driver");
		} catch(ClassNotFoundException e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	public static Connection getConnection() throws SQLException {   //建立连接方法
		return DriverManager.getConnection(url, user, password);
	}
	
	public static void free(ResultSet rs, Statement st, Connection conn){   //释放资源
		try{
			if(rs != null)
				rs.close();
		} catch(Exception e){
			e.printStackTrace();
		}finally{
			try{
				if(st != null)
					st.close();
			} catch(Exception e){
				e.printStackTrace();
			}finally{
				if(conn != null)
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
			}
		}
	}
}




调用:

Connection conn = JdbcUtils.getConnection();

Statement st = (Statement) conn.createStatement();

你可能感兴趣的:(数据库-sql)