반응형
연결 개체를 반환하는이 클래스를 만들었습니다. MySQL 데이터베이스를 사용했습니다.
public class Connect_db {
public Connection getConnection(String db_name,String user_name,String password)
{
Connection con=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
이제 내가 원하는 것은이 클래스를 한 번 인스턴스화하고 연결 개체를 얻는 것입니다. And I want to use this same object in entire application. 또 다른 솔루션도 높이 평가 될 것입니다.
해결 방법
싱글 톤 패턴이 필요하다고 가정합니다. 여기에 간단한 예가 있습니다.
public class Connect_db {
static Connection con=null;
public static Connection getConnection()
{
if (con != null) return con;
// get db, user, pass from settings file
return getConnection(db, user, pass);
}
private static Connection getConnection(String db_name,String user_name,String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/"+db_name+"?user="+user_name+"&password="+password);
}
catch(Exception e)
{
e.printStackTrace();
}
return con;
}
}
그러면 다음과 같은 연결을 사용할 수 있습니다.
Connect_db.getConnection().somemethods();
그러나 여러 스레드가 데이터베이스에 요청을 시도 할 때 다중 스레드 환경에서 이것이 어떻게 작동하는지 생각해야합니다.
참조 페이지 https://stackoverflow.com/questions/20666658
반응형
'MySql' 카테고리의 다른 글
MySQL HTML 에코 내에서 변수로 큰 따옴표를 이스케이프 (0) | 2020.12.15 |
---|---|
MySQL 실행중인 mysql 쿼리를 중지하는 방법 (0) | 2020.12.15 |
MySQL 열 수가 행 1의 값 수와 일치하지 않습니다. (0) | 2020.12.15 |
MySQL mysql_num_rows (); (0) | 2020.12.15 |
MySQL PDOException SQLSTATE [HY000] [2002] 해당 파일 또는 디렉토리가 없습니다. (0) | 2020.12.15 |
댓글