我写了一个单例类来获取连接。但是,我无法使用 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);
}
最佳答案
如果你想有效地使用多个连接,你可能会在 connection pool 之后:
In software engineering, a connection pool is a cache of database connections maintained so that the connections can be reused when future requests to the database are required. Connection pools are used to enhance the performance of executing commands on a database.
Singleton
将返回 许多 连接违背了 Singleton
的目的,它的任务是在任何时候提供相同的实例打电话。
我建议你看看this以前的 SO 线程,其中讨论了各种连接池库。
关于java - 如何使用 Singleton 类来获得多个连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11734040/