更新时间:2023-11-30 12:38:04
您可以像这样使用设计模式Singleton Connection:
You can use the design pattern Singleton Connection like this :
1-创建一个类SingletonConnection.java,如下所示:
1- create a class SingletonConnection.java look like that :
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.EmptyStackException;
public class SingletonConnection {
private static Connection connection = null ;
static
{
try{
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection
("jdbc:mysql://localhost:3306/gestion_comptes","root","");
}catch(Exception ex)
{
}
}
public static Connection getConnection() throws Exception {
return connection;
}
}
并在你的其他类称之为:
And in your other class call it like that :
public class DaoImpl{
public Connection connection = SingletonConnection.getConnection();
public DaoImpl() throws Exception
{
if(connection==null)
throw new Exception("impossible de se connecter à la base de données");
}
}