在Java应用程序中打开和返回数据库连接的最佳方法? [英] Best way to open and return a database connection in a Java application?

查看:134
本文介绍了在Java应用程序中打开和返回数据库连接的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提出了以下实用程序类:

I have come up with the following utility class:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySqlConnection
{
    private static String dbUrl = "jdbc:mysql://localhost:3306/database";
    private static String dbUsername = "root";
    private static String dbPassword = "mysql";

    public static Connection getConnection()
    {
        Connection connection = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
        } catch (ClassNotFoundException e) {
            System.out.println("Could not load JDBC driver: " + e.getMessage());
        } catch (SQLException e) {
            System.out.println("Could not connect to DB: " + e.getMessage());
        }
        return connection;
    }
}

问题是:我不想要从我的方法返回 null ,因为通过这样做我强制我的调用者执行 if(connection!= null){...} 每次打开时都要检查并想要使用连接。我发现这些空检查容易出错,并且不惜一切代价避免它们。我可以遵循哪种方法来管理我的应用程序中的数据库连接?

The problem is: I do not want to return null from my method, because by doing so I force my callers to do a if (connection != null) {...} check every time they open and want to use a connection. I find these null checks to be error prone and want to avoid them at all costs. What other approach could I follow to manage database connections in my application?

推荐答案

首先,从JDBC 4.0 / Java 6开始,不再需要调用 Class.forName()
请参阅Class.forName()必要

First of all, as of JDBC 4.0 / Java 6, calling Class.forName() is no longer necessary.
(See is Class.forName() necessary)

接下来,不要埋没例外情况。将它们扔到堆栈中,让调用者决定应该如何处理异常。根据何时调用 getConnection(),您可能需要:

Next, don't bury the exceptions. Throw them up the stack, and let the callers decide how the exceptions should be handled. Depending on when getConnection() is being called you might want to:


  • 显示用户的错误弹出框

  • 为连接尝试不同的数据库

  • 运行脚本以尝试检查数据库的状态并尝试如果它似乎已关闭则重新启动它

  • 完全重试getConnection()

  • Display an error popup box to the user
  • Try a different database for a connection
  • Run a script to try and check the status of the database and attempt to restart it if it appears to be down
  • Retry getConnection() completely

我的观点存在,不要害怕将异常抛出堆栈并让调用者适当地处理异常。

My point being, don't be afraid to throw Exceptions up the stack and let the caller handle the Exception appropriately.

所有这些,您的 getConnection()方法应该只需要存储您的数据库URL,用户名和密码。

All that being said, your getConnection() method should just need to store your DB URL, username, and password.

public class MySqlConnection
{
    private static String dbUrl = "jdbc:mysql://localhost:3306/database";
    private static String dbUsername = "root";
    private static String dbPassword = "mysql";

    public static Connection getConnection() throws SQLException
    {
        return DriverManager.getConnection(dbUrl, dbUsername, dbPassword);
    }
}

实际上, getConnection() 很少会抛出SQLException。我曾经看到它抛出SQLException的唯一情况是因为凭据不正确或数据库已关闭。

Realistically, getConnection() will very very rarely throw an SQLException. The only scenario I've ever seen it throw an SQLException is because credentials were incorrect or the database was down.

这篇关于在Java应用程序中打开和返回数据库连接的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆