I wrote a Singleton class for getting connections. However, I cannot get connections using Singleton.
I want to use my Singleton for getting several connections and to make query to database, using the connection Singleton. I always try several ways for this, and no success.
This is my Singleton class:
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;
}
}
Now, I get the connections:
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);
}
If you want to use multiple connections efficiently you might be after a connection pool:
Having a
Singletonwhich will return many connections defies the purpose of theSingleton, whose task is to provide the same instance whenever it is called.I recommend you take a look at this previous SO thread where various connection pool libraries are discussed.