【问题标题】:How to use Singleton class for to get connections multiple?如何使用 Singleton 类来获得多个连接?
【发布时间】:2012-07-31 06:00:26
【问题描述】:

我写了一个单例类来获取连接。但是,我无法使用 Singleton 获得连接。

我想使用我的 Singleton 获取多个连接并使用连接 Singleton 查询数据库。为此我总是尝试几种方法,但都没有成功。

这是我的单例类:

import java.sql.*;

public class ConnectDB {

private static Connection connect;
private static ConnectDB instance;

private ConnectDB()
{

    try {

        Class.forName("com.mysql.jdbc.Driver");
        //connect DB
        connect = DriverManager.getConnection("jdbc:mysql://ip/database","root","password");

    }

    catch(SQLException e)
    {
        System.err.println(e.getMessage());

    }

    catch(ClassNotFoundException e)
    {

        System.err.println(e.getMessage());

    }   
}

  public static ConnectDB getInstance()
  {

      if(instance == null) {

          instance = new ConnectDB();

      }

      return instance;

  }

}

现在,我得到了连接:

 public class NameClass {




public void getInfoDatabase()
{   

       Connection cnn = ConnectDB.getConnection();
       PreparedStatement ps;
       ResultSet rs;

       try {

           ps = cnn.prepareStatement("select *  from tables");

           rs = ps.executeQuery();

           while(rs.next())
           {

               String tables = rs.getString("table1");
               System.out.println(tables);
           }

【问题讨论】:

  • 多个单身人士?有点违背了拥有单身人士的目的......
  • 您在哪里遇到过问题?除了你可能想在单例类中编写一个类似 execStmtL(Stmt) 的方法,所以你可以直接从这里运行它?
  • 你在哪里调用 ConnectDB.getInstance() ?不是这样,这个实现看起来很糟糕——我不喜欢静态连接对象的外观。那不应该是 ConnectDB 的实例变量吗?

标签: java database design-patterns jdbc


【解决方案1】:

如果您想有效地使用多个连接,您可能需要connection pool

在软件工程中,连接池是数据库的缓存 保持连接,以便在连接时可以重用 未来对数据库的请求是必需的。连接池是 用于提高在数据库上执行命令的性能。

拥有一个将返回许多个连接的Singleton 违背了Singleton 的目的,它的任务是在调用时提供相同的实例。

我建议您查看 this 以前的 SO 线程,其中讨论了各种连接池库。

【讨论】:

    【解决方案2】:

    我的方式是这个 DBConnection 是一个单例类。并且这个用法在 ContactDAO 类中。

    public class DBConnection{
    
        private static DBConnection instance;
        private String url="jdbc:oracle:thin:@192.168.10.32:1521:orcl";
        private String login="kit";
        private String pass="1234";
    
        private DBConnection(){
    
            try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        public static Connection getConnection() throws SQLException {
            if (instance == null) {
                instance = new DBConnection();
                System.out.println(" Connection  - - - - - - - -  New DBConnection created");
            }
            try {
                return DriverManager.getConnection(instance.url, instance.login,instance.pass);
            } catch (SQLException e) {
                throw e;
            }
        }
    
        public static void close(Connection connection)
        {
            try {
                if (connection != null) {
                    connection.close();
                    connection=null;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    
    }
    

    ********* 联系DAO *************

    public class ContactDAO {
    
    
            public List<Contact> findAll() {
                List<Contact> list = new ArrayList<Contact>();
                Connection c = null;
                String sql = "SELECT * FROM KIT.CONTACT";
                try {
                    c = DBConnection.getConnection();
                    Statement s = c.createStatement();
                    ResultSet rs = s.executeQuery(sql);
                    while (rs.next()) {
                        list.add(processRow(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
                return list;
            }
    
            public List<Contact> findByCity(String city) {
                List<Contact> list = new ArrayList<Contact>();
                Connection c = null;
                String sql = "SELECT * FROM KIT.CONTACT as e " + "WHERE UPPER(city) LIKE ? ";
                try {
                    c = DBConnection.getConnection();
                    PreparedStatement ps = c.prepareStatement(sql);
                    ps.setString(1, "%" + city.toUpperCase() + "%");
                    ResultSet rs = ps.executeQuery();
                    while (rs.next()) {
                        list.add(processRow(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
                return list;
            }
    
            public Contact findById(int id) {
                String sql = "SELECT * FROM KIT.CONTACT WHERE id = ?";
                Contact contact = null;
                Connection c = null;
                try {
                    c = DBConnection.getConnection();
                    PreparedStatement ps = c.prepareStatement(sql);
                    ps.setInt(1, id);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        contact = processRow(rs);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
                return contact;
            }
    
            public Contact save(Contact contact) {
                return contact.getId() > 0 ? update(contact) : insert(contact);
            }
    
            public Contact insert(Contact contact) {
                Connection c = null;
                PreparedStatement ps = null;
                try {
                    c = DBConnection.getConnection();
                    ps = c.prepareStatement(
                            "INSERT INTO KIT.CONTACT (country, city, address, photo,fk_user) VALUES (?, ?, ?, ?, ?)",
                            new String[] { "ID" });
    
                    ps.setString(1, contact.getCountry());
                    ps.setString(2, contact.getCity());
                    ps.setString(3, contact.getAddress());
                    ps.setString(4, contact.getPhoto());
                    ps.setInt(5, contact.getFk_user());
    
                    ps.executeUpdate();
    
                    ResultSet rs = ps.getGeneratedKeys();
                    while(rs.next()){
                    int id = rs.getInt(1);
                    contact.setId(id);
                    }
    
    
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
                return contact;
            }
    
            public Contact update(Contact contact) {
                Connection c = null;
                try {
                    c = DBConnection.getConnection();
                    PreparedStatement ps = c
                            .prepareStatement("UPDATE KIT.CONTACT SET country=?, city=?, address=?, photo=?  WHERE id=?");
                    ps.setString(1, contact.getCountry());
                    ps.setString(2, contact.getCity());
                    ps.setString(3, contact.getAddress());
                    ps.setString(4, contact.getPhoto());
    
                    ps.setInt(5, contact.getId());
                    ps.executeUpdate();
                } catch (SQLException e) {
                    e.printStackTrace();
                    System.out.println("contactDAO update exception");
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
                return contact;
            }
    
            public boolean remove(int id) {
                Connection c = null;
                try {
                    c = DBConnection.getConnection();
                    PreparedStatement ps = c
                            .prepareStatement("DELETE FROM KIT.CONTACT WHERE id=?");
                    ps.setInt(1, id);
                    int count = ps.executeUpdate();
                    return count == 1;
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                } finally {
                    DBConnection.close(c);
                }
            }
    
            protected Contact processRow(ResultSet rs) throws SQLException {
                Contact contact = new Contact();
                contact.setId(rs.getInt("id"));
                contact.setCountry(rs.getString("country"));
                contact.setCity(rs.getString("city"));
                contact.setAddress(rs.getString("address"));
                contact.setPhoto(rs.getString("photo"));
    
                return contact;
    
            }
    
    
    
    
    
    
    
        }
    

    【讨论】:

      【解决方案3】:

      最好有一个像ComboPooledDataSource 这样的单例连接池,然后从中获得多个连接。

      【讨论】:

        猜你喜欢
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        • 2011-07-08
        • 2013-10-06
        • 2015-10-21
        • 1970-01-01
        • 1970-01-01
        • 2014-03-30
        相关资源
        最近更新 更多