import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* 连接|关闭 数据库方法封装
*/
public class JDBCUtil {
/*
* 获得MySQl的连接
*/
public static Connection getConnection(){
try {
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","123456");
} catch (ClassNotFoundException e) {
e.printStackTrace();
return null;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
/*
* 关闭rs,stmt,ps,conn
*/
public static void close(ResultSet rs,PreparedStatement stmt,Connection conn){
//关闭顺序遵循:ResultSet-->Statement->Connection
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试方法封装是否可用
import java.sql.*;
public class TestJDBCUtil {
/**
* 测试方法封装是否可用
*/
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtil.getConnection();
ps = conn.prepareStatement("select * from user where uid=?");
ps.setInt(1, 1);
if(ps.execute()){
rs = ps.getResultSet();
while(rs.next()){
System.out.println(rs.getInt(1));
}
}
System.out.println("TestJDBCUtil.main()");
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtil.close(rs, ps, conn);
}
}
}