Article directory
IDE and necessary configuration
IDE: IntelliJ IDEA 2023.1
Necessary configuration:
1. Install JDK and configure environment variables
2. Import the drivers required for MYSQL database
If it is not imported, you can refer to this article to download and import the driver package required for the MySQL database in IDEA.
Database connection code
package com.sxt.utils;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.sql.*;
public class DBHelper {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/数据库名字记得修改覆盖?useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true";
/**连接数据库的方法**/
public static Connection getConnection() throws ClassNotFoundException, SQLException {
// 加载数据库驱动
Class.forName(driver);
Connection con = DriverManager.getConnection(url,"root","123456");
//数据库的用户名和密码,root是用户名位置,123456是密码位置,一般需要修改
return con;
}
/**关闭数据库的方法**/
public static void close(Connection con, PreparedStatement ps, ResultSet rs){
// 关闭资源,避免出现异常
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(ps != null){
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con != null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// 测试
public static void main(String[] args){
try {
System.out.println("---开始---");
DBHelper.getConnection();
System.out.println("---测试---");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
This is the end