import java.sql.*;
public class DBManager {
// mysql驅動
private static final String driverName="com.mysql.jdbc.Driver";
// 資料庫連接配接位址localhost:3307/school 改成自己的端口和資料庫名稱
private static final String url="jdbc:mysql://localhost:3307/school?useUnicode=true&characterEncoding=utf-8";
// 使用者名和密碼
private static final String user="root",pwd="admin";
public static Connection getConnection(){
try {
// 加載驅動
Class.forName(driverName);
// 連接配接資料庫 如上設定的url user pwd 分别為 url 連接配接位址 user 使用者名 pwd 密碼
return DriverManager.getConnection(url, user, pwd);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static int executeUpdate(String sql){
Connection conn=null;
Statement sta=null;
try {
conn = getConnection();
// 執行個體化Statement對象
sta = conn.createStatement();
// 執行資料庫更新操作
return sta.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
return e.getErrorCode()*(-1);
}
finally{
closeAll(conn,sta,null);
}
}
// 釋放資源
public static void closeAll(Connection conn,Statement sta,ResultSet set){
try {
if(set !=null)
set.close();
if(sta!=null)
sta.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}