如果我使用单例类进行数据库连接,一个用户可以为每个人关闭连接吗?

问题描述 投票:15回答:5

我写了一个单例类来获取数据库连接。

现在我的问题是:假设有100个用户访问该应用程序。如果一个用户关闭了连接,对于其他99个用户,是否会关闭连接?

这是我的示例程序,它使用单例类来获取数据库连接:

public class GetConnection {

    private GetConnection() { }

    public Connection getConnection() {
        Context ctx = new InitialContext();
        DataSource ds = ctx.lookup("jndifordbconc");
        Connection con = ds.getConnection();
        return con;
    }

    public static  GetConnection   getInstancetoGetConnection () {
        // which gives GetConnection class instance to call getConnection() on this .
    }
}

请指导我。

java design-patterns jdbc
5个回答
24
投票

只要你没有在Connection电话上返回相同的getConnection()实例,那么就没什么好担心的了。然后每个调用者都会获得自己的实例。到目前为止,您正在为每个getConnection()调用创建一个全新的连接,因此不会返回一些静态或实例变量。所以这很安全。

但是,这种方法很笨拙。它不需要是单身人士。辅助工具/实用工具类也很好。或者,如果您想要更多抽象,则由抽象工厂返回连接管理器。我只会在类初始化期间更改它以获取数据源,而不是每次在getConnection()中获取数据源。无论如何,它每次都是相同的实例。保持便宜。这是一个基本的启动示例:

public class Database {

    private static DataSource dataSource;

    static {
        try {
            dataSource = new InitialContext().lookup("jndifordbconc");
        }
        catch (NamingException e) { 
            throw new ExceptionInInitializerError("'jndifordbconc' not found in JNDI", e);
        }
    }

    public static Connection getConnection() {
        return dataSource.getConnection();
    }

}

根据普通的JDBC习语使用如下。

public List<Entity> list() throws SQLException {
    List<Entity> entities = new ArrayList<Entity>();

    try (
        Connection connection = Database.getConnection();
        PreparedStatement statement = connection.prepareStatement("SELECT id, foo, bar FROM entity");
        ResultSet resultSet = statement.executeQuery();
    ) {
        while (resultSet.next()) {
            Entity entity = new Entity();
            entity.setId(resultSet.getLong("id"));
            entity.setFoo(resultSet.getString("foo"));
            entity.setBar(resultSet.getString("bar"));
            entities.add(entity);
        }
    }

    return entities;
}

See also:


2
投票
package es.sm2.conexion;

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

public class ConexionTest {

    static Connection getConnection() throws Exception {

        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "userparatest";
        String password = "userparatest";

        Class.forName(driver).newInstance();
        Connection conn = DriverManager.getConnection(url + dbName, userName,password);

        return conn;
    }
}

关闭连接

public static void closeConnection(Connection conn) {

        try {

            conn.close();

        } catch (SQLException e) {

        }

    }

要呼叫连接:

package conexion.uno;

import java.sql.*;

import es.sm2.conexion.ConexionTest;

public class LLamadorConexion {

    public void llamada() {
        Connection conn = null;
        PreparedStatement statement = null;
        ResultSet resultado = null;
        String query = "SELECT * FROM empleados";

        try {
            conn = ConexionTest.getConnection();
            statement = conn.prepareStatement(query);
            resultado = statement.executeQuery();

            while (resultado.next()) {
                System.out.println(resultado.getString(1) + "\t" + resultado.getString(2) + "\t" + resultado.getString(3) + "\t" );
            }
        } 
        catch (Exception e) {
            System.err.println("El porque del cascar: " + e.getMessage());
        } 
        finally {
            ConexionTest.closeConnection(conn);

        }
    }
}

1
投票

下面的代码是一个经过工作和测试的Singleton Pattern for Java。

public class Database {

    private static Database dbIsntance;
    private static Connection con ;
    private static Statement stmt;


    private Database() {
      // private constructor //
    }

    public static Database getInstance(){
    if(dbIsntance==null){
        dbIsntance= new Database();
    }
    return dbIsntance;
    }

    public  Connection getConnection(){

        if(con==null){
            try {
                String host = "jdbc:derby://localhost:1527/yourdatabasename";
                String username = "yourusername";
                String password = "yourpassword";
                con = DriverManager.getConnection( host, username, password );
            } catch (SQLException ex) {
                Logger.getLogger(Database.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return con;
    }

虽然在任何类中获取Connection只是使用下面的行

Connection con = Database.getInstance().getConnection();

希望它可以帮助:)


1
投票

伟大的帖子,farhangdon!然而,我发现它有点麻烦,因为一旦你关闭了连接,你没有其他方法可以开始一个新的连接。一个小技巧将解决它:

if(con==null)替换if(con==null || con.isClosed())


0
投票
import java.sql.Connection;
import java.sql.DriverManager;

public class sql11 {

    static Connection getConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/ics", "root", "077");
        return c;

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.