import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
* 連接|關(guān)閉 數(shù)據(jù)庫方法封裝
*/
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;
}
}
/*
* 關(guān)閉rs,stmt,ps,conn
*/
public static void close(ResultSet rs,PreparedStatement stmt,Connection conn){
//關(guān)閉順序遵循: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);
}
}
}