JDBC基礎:https://blog.csdn.net/weixin_44893902/article/details/106746880
Dbconnection工具類(包含了連線,增刪改查,關閉)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import com.mysql.jdbc.Statement;
public class DbConnection {
//驅動類的類名
private static final String DRIVERNAME="com.mysql.jdbc.Driver";
//連線資料的URL路徑
private static final String URL="jdbc:mysql://127.0.0.1:3306/moviedb";
//資料庫登入賬號
private static final String USER="root";
//資料庫登入密碼
private static final String PASSWORD="root123";
//載入驅動
static{
try {
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//獲取資料庫連線
public static Connection getConnection() {
try {
return DriverManager.getConnection(URL,USER,PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
//查詢
public static ResultSet query(String sql) {
System.out.println(sql);
//獲取連線
Connection connection=getConnection();
PreparedStatement psd;
try {
psd = connection.prepareStatement(sql);
return psd.executeQuery();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"執行語句出錯\n"+e.toString());
e.printStackTrace();
}
return null;
}
//增、刪、改、查
public static int updataInfo(String sql) {
System.out.println(sql);
//獲取連線
Connection connection=getConnection();
try {
PreparedStatement psd=connection.prepareStatement(sql);
return psd.executeUpdate();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null,"執行語句出錯\n"+e.toString());
e.printStackTrace();
}
return 0;
}
//關閉連線
public static void colse(ResultSet rs,Statement stmt,Connection conn) throws Exception{
try {
if (rs != null){
rs.close();
}
if (stmt != null){
stmt.cancel();
}
if (conn != null) { conn.close(); }
} catch (Exception e) {
e.printStackTrace(); throw new Exception();
}
}
}