import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnectionExample {
// JDBC URL, 用户名和密码
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USERNAME = "root";
private static final String PASSWORD = "password";
public static void main(String[] args) {
// 1. 加载JDBC驱动程序
try {
Class.forName("com.mysql.cj.jdbc.Driver");
System.out.println("JDBC Driver loaded successfully.");
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
e.printStackTrace();
return;
}
// 2. 建立数据库连接
Connection connection = null;
try {
connection = DriverManager.getConnection(JDBC_URL, USERNAME, PASSWORD);
System.out.println("Connected to the database successfully.");
// 在这里可以执行SQL查询或更新操作
} catch (SQLException e) {
System.out.println("Failed to connect to the database.");
e.printStackTrace();
} finally {
// 3. 关闭连接
if (connection != null) {
try {
connection.close();
System.out.println("Database connection closed.");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
加载JDBC驱动程序:使用 Class.forName() 方法来加载 MySQL 的 JDBC 驱动程序。这一步是为了确保 Java 程序能够找到并使用正确的驱动程序来与数据库通信。
建立数据库连接:通过 DriverManager.getConnection() 方法,传入数据库的 URL、用户名和密码,建立与数据库的连接。
关闭连接:在操作完成后,务必关闭数据库连接以释放资源。使用 finally 块来确保即使发生异常也能正确关闭连接。
异常处理:使用 try-catch 结构来捕获并处理可能发生的异常,如找不到驱动程序或连接失败等。
JDBC URL:jdbc:mysql://localhost:3306/mydatabase 是一个典型的 MySQL 数据库连接字符串,其中 localhost 是数据库服务器地址,3306 是 MySQL 默认端口,mydatabase 是数据库名称。
上一篇:java list 取交集
下一篇:java字符串转时间戳
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站