-
Notifications
You must be signed in to change notification settings - Fork 0
/
DAO_Factory.java
101 lines (87 loc) · 2.42 KB
/
DAO_Factory.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
import java.lang.*;
import java.sql.*;
public class DAO_Factory{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/librarydb";
static final String USER = "root";
static final String PASS = "root";
Connection dbconnection = null;
BookDAO bookDAO = null;
BookCopyDAO bookcopyDAO = null;
MemberDAO memberDAO = null;
boolean activeConnection = false;
public DAO_Factory()
{
dbconnection = null;
activeConnection = false;
}
public void activateConnection() throws Exception
{
if( activeConnection == true )
{
throw new Exception("Connection already active");
}
System.out.println("Connecting to database...");
try
{
Class.forName("com.mysql.jdbc.Driver");
dbconnection = DriverManager.getConnection(DB_URL,USER,PASS);
activeConnection = true;
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
catch (SQLException ex)
{
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
public BookDAO getBookDAO() throws Exception
{
if( activeConnection == false )
throw new Exception("Connection not activated...");
if( bookDAO == null )
bookDAO = new BookDAO_JDBC( dbconnection );
return bookDAO;
}
public BookCopyDAO getBookCopyDAO() throws Exception
{
if( activeConnection == false )
throw new Exception("Connection not activated...");
if( bookcopyDAO == null )
bookcopyDAO = new BookCopyDAO_JDBC( dbconnection );
return bookcopyDAO;
}
public MemberDAO getMemberDAO() throws Exception
{
if( activeConnection == false )
throw new Exception("Connection not activated...");
if( memberDAO == null )
memberDAO = new MemberDAO_JDBC( dbconnection );
return memberDAO;
}
public void deactivateConnection()
{
// Okay to keep deactivating an already deactivated connection
activeConnection = false;
if( dbconnection != null ){
try{
dbconnection.close();
dbconnection = null;
bookDAO = null;
bookcopyDAO = null;
memberDAO = null;
}
catch (SQLException ex) {
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
}
}
};