Java连接数据库:异常处理与优化

原创 偏执的太偏执、 2024-11-25 13:51 72阅读 0赞

在Java中,连接数据库主要使用JDBC(Java Database Connectivity)接口。以下是一个简单的示例,包括异常处理和优化:

  1. 异常处理:
    ```java
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;

public class DatabaseConnection {
private static final String DB_URL = “jdbc:mysql://localhost:3306/mydatabase”;
private static final String USER = “username”;
private static final String PASSWORD = “password”;

  1. public static Connection getConnection() throws SQLException {
  2. Connection connection = null;
  3. try {
  4. // 注册JDBC驱动
  5. Class.forName("com.mysql.jdbc.Driver");
  6. // 建立连接
  7. connection = DriverManager.getConnection(DB_URL, USER, PASSWORD));
  8. if (connection != null) {
  9. System.out.println("Database connection successful.");
  10. }
  11. } catch (Exception e) {
  12. System.err.println("Error occurred while connecting to database: " + e.getMessage());
  13. if (connection != null) {
  14. connection.close();
  15. }
  16. throw new SQLException(e.getMessage(), e));
  17. }
  18. return connection;
  19. }
  20. // 优化:使用连接池
  21. private static final Object POOL_LOCK = new Object();
  22. private static ConnectionPool getConnectionPool() throws SQLException {
  23. ConnectionPool pool = null;
  24. synchronized (POOL_LOCK) {
  25. if (pool == null) {
  26. // 初始化连接池
  27. pool = new SimpleConnectionPool();
  28. }
  29. }
  30. return pool.getConnection();
  31. }
  32. public static void main(String[] args) {
  33. try {
  34. // 使用优化后的连接池
  35. Connection connection = getConnectionPool().getConnection();
  36. if (connection != null) {
  37. System.out.println("Database connection successful.");
  38. // 处理数据库操作...
  39. } else {
  40. System.out.println("Connection to database pool failed.");
  41. }
  42. } catch (SQLException e) {
  43. System.err.println("Error occurred while connecting to database: " + e.getMessage());
  44. if (connection != null) {
  45. connection.close();
  46. }
  47. throw new RuntimeException(e.getMessage(), e));
  48. }
  49. }

}
```

  1. 优化:
  • 使用连接池(如SimpleConnectionPool)来管理数据库连接,避免频繁创建和销毁连接。
  • 当出现异常时,确保关闭数据库连接,防止资源泄露。

这只是一个基本示例,实际使用中可能需要根据数据库类型、配置等进行调整。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,72人围观)

还没有评论,来说两句吧...

相关阅读