JDBC 技术 | Java连接MySQL数据库(零基础保姆级超全详解)
    		       		warning:
    		            这篇文章距离上次修改已过447天,其中的内容可能已经有所变动。
    		        
        		                
                
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class Main {
    static final String DB_URL = "jdbc:mysql://localhost:3306/数据库名";
    static final String USER = "用户名";
    static final String PASS = "密码";
 
    public static void main(String[] args) {
        // 注册 JDBC 驱动
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return;
        }
 
        // 打开连接
        try (Connection connection = DriverManager.getConnection(DB_URL, USER, PASS)) {
            // 操作数据库
            // ...
 
            System.out.println("连接成功!");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}这段代码展示了如何使用JDBC连接MySQL数据库的基本步骤。首先,通过Class.forName()注册JDBC驱动。然后,使用DriverManager.getConnection()方法建立连接。最后,在try-with-resources语句中管理连接的关闭,以确保即使发生异常也能正确关闭资源。
评论已关闭