package com.tesjd;
import java.sql.*;
//已測試過
public class DB {
//在使用時都要加載驅動因此放在靜態代碼塊中
static {
try{
Class.forName("com.mysql.jdbc.Driver");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
public static Connection getCon(){
Connection con= null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/work?user=root&password=admin");
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
public static void closeCon(Connection con){
try {
if(con!=null){ java
//有的能夠有con = null,但我運行的時候出現了java.lang.NullPointException異常 因此註釋了 mysql
//con= null;
con.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static Statement getSta(Connection con){
Statement sta= null;
try {
sta=con.createStatement();
}catch(SQLException e){
e.printStackTrace();
}
return sta;
}
public static PreparedStatement getPsta(Connection con,String sql){
PreparedStatement psta= null;
try {
psta= con.prepareStatement(sql);
}catch(SQLException e){
e.printStackTrace();
}
return psta;
}
public static void closeSta(Statement sta){
try {
if(sta!=null){
//sta=null;
sta.close() ;
}
}catch(SQLException e){
e.printStackTrace();
}
}
public static ResultSet executeQuery (Statement sta, String sql)
{
ResultSet res= null;
try {
res= sta.executeQuery(sql); sql
}catch(Exception e){e.printStackTrace();
return res;
}
public static void closeRes(ResultSet res){
try{if(res!=null){
// res=null; //不要亂寫 只要這裏寫了null就會出現nullpoing錯誤
res.close();
}
}catch(SQLException e){e.printStackTrace();}
} 測試
//重載上面的executeQuery()方法 spa
public static ResultSet executeQuery(Connection con,String sql){ ResultSet res= null; try { res= con.createStatement().executeQuery(sql); }catch(SQLException e){e.printStackTrace();} return res; } }