import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCConnectionExample {
// JDBC URL, username, and password of MySQL server
private static final String URL = "jdbc:mysql://localhost:3306/mydatabase";
private static final String USER = "root";
private static final String PASSWORD = "password";
// JDBC variables for opening and managing connection
private static Connection connection;
public static void main(String[] args) {
// Establishing the connection to the database
try {
// Initialize the connection object
connection = DriverManager.getConnection(URL, USER, PASSWORD);
if (connection != null) {
System.out.println("Connected to the database successfully.");
}
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
} finally {
// Closing the connection
try {
if (connection != null && !connection.isClosed()) {
connection.close();
System.out.println("Connection closed.");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
java.sql.Connection, java.sql.DriverManager, 和 java.sql.SQLException 是用于数据库连接和异常处理的类。DriverManager.getConnection() 方法来创建一个到数据库的连接。如果连接成功,会打印一条消息。SQLException 异常。finally 块中确保连接在使用后被正确关闭。这段代码展示了如何使用Java通过JDBC(Java Database Connectivity)与MySQL数据库建立连接,并进行基本的连接管理和错误处理。
上一篇:java加密算法
下一篇:java面向对象的特征
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站