]> git.mxchange.org Git - jaddressbook-lib.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/mysql/MySqlDatabaseBackend.java
Handled / throw some exceptions
[jaddressbook-lib.git] / Addressbook / src / org / mxchange / addressbook / database / backend / mysql / MySqlDatabaseBackend.java
1 /*
2  * Copyright (C) 2015 Roland Haeder
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  */
17 package org.mxchange.addressbook.database.backend.mysql;
18
19 import java.io.IOException;
20 import java.sql.Connection;
21 import java.sql.DriverManager;
22 import java.sql.PreparedStatement;
23 import java.sql.ResultSet;
24 import java.sql.SQLException;
25 import java.text.MessageFormat;
26 import java.util.Iterator;
27 import org.mxchange.addressbook.contact.Contact;
28 import org.mxchange.addressbook.database.backend.BaseDatabaseBackend;
29 import org.mxchange.addressbook.database.backend.DatabaseBackend;
30 import org.mxchange.addressbook.database.storage.Storeable;
31 import org.mxchange.addressbook.exceptions.BadTokenException;
32 import org.mxchange.addressbook.exceptions.UnsupportedDatabaseDriverException;
33
34 /**
35  * A backend class for MySQL connections
36  *
37  * @author Roland Haeder
38  */
39 public class MySqlDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
40         /**
41          * An instance of a datbase connection
42          */
43         private static Connection connection;
44
45         /**
46          * Prepared statement for full row count
47          */
48         private PreparedStatement totalRowCount;
49
50         /**
51          * Constructor with table name
52          * 
53          * @param tableName Table to access
54          * @throws org.mxchange.addressbook.exceptions.UnsupportedDatabaseDriverException
55          */
56         public MySqlDatabaseBackend (final String tableName) throws UnsupportedDatabaseDriverException {
57                 // Validate driver
58                 this.validateDriver("mysql"); //NOI18N
59
60                 // Now that the driver is there, set the table name
61                 this.setTableName(tableName);
62         }
63
64         @Override
65         public void connectToDatabase () throws SQLException {
66                 // Trace message
67                 this.getLogger().trace("CALLED!"); //NOI18N
68
69                 // Is the connection already there?
70                 if (MySqlDatabaseBackend.connection instanceof Connection) {
71                         // Already connected
72                         this.getLogger().debug("Connection is already established."); //NOI18N
73
74                         // No need to connect
75                         return;
76                 }
77
78                 // Generate connection string
79                 String connect = String.format("jdbc:mysql://%s/%s", //NOI18N
80                                 this.getProperty("database.mysql.host"), //NOI18N
81                                 this.getProperty("database.mysql.dbname") //NOI18N
82                 );
83
84                 // Debug message
85                 this.getLogger().debug(MessageFormat.format("Attempting to connect to {0} ...", connect)); //NOI18N
86
87                 // Now get a connection instance back
88                 MySqlDatabaseBackend.connection = DriverManager.getConnection(
89                                 connect,
90                                 this.getProperty("database.mysql.login"), //NOI18N
91                                 this.getProperty("database.mysql.password") //NOI18N
92                 );
93
94                 // Is the connection really up?
95                 if (MySqlDatabaseBackend.connection.isClosed()) {
96                         // Connection is closed again
97                         throw new SQLException("Connection is closed."); //NOI18N
98                 }
99
100                 // Debug message
101                 this.getLogger().debug("Connection is up, preparing some statements ..."); //NOI18N
102
103                 // Here, the connection is established, so prepare some statements
104                 this.totalRowCount = MySqlDatabaseBackend.connection.prepareStatement(String.format("SELECT COUNT(`id`) AS `cnt` FROM `%s` LIMIT 1", this.getTableName())); //NOI18N
105
106                 // Trace message
107                 this.getLogger().trace("EXIT!"); //NOI18N
108         }
109
110         @Override
111         @Deprecated
112         public Iterator<Contact> contactIterator () throws BadTokenException {
113                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
114         }
115
116         @Override
117         public void doShutdown () {
118                 // This should not happen:
119                 assert(MySqlDatabaseBackend.connection instanceof Connection) : MessageFormat.format("connection is not valid: {0}", MySqlDatabaseBackend.connection); //NOI18N
120
121                 try {
122                         // Close down database connection
123                         MySqlDatabaseBackend.connection.close();
124                 } catch (final SQLException ex) {
125                         // Something happened during close()
126                         this.abortProgramWithException(ex);
127                 }
128         }
129
130         @Override
131         public int getTotalCount () throws SQLException {
132                 // Trace message
133                 this.getLogger().trace(MessageFormat.format("tableName={0} - CALLED!", this.getTableName())); //NOI18N
134
135                 // Nothing counted by default
136                 int count = 0;
137
138                 // Prepared statements are cool ...
139                 if (this.totalRowCount.execute()) {
140                         // Did fully work, so get result set
141                         ResultSet set = this.totalRowCount.getResultSet();
142
143                         // First rewind it
144                         assert(set.last()) : ": last() failed"; //NOI18N
145
146                         // Get integer from 'cnt' alias (see statement)
147                         count = set.getInt("cnt"); //NOI18N
148
149                         // Debug message
150                         this.getLogger().debug(MessageFormat.format("count={0}", count)); //NOI18N
151
152                         // Go back to beginning
153                         set.beforeFirst();
154                 } else {
155                         // Empty result
156                         this.getLogger().warn(MessageFormat.format("COUNT() query didn't return any result on table {0}.", this.getTableName())); //NOI18N
157                 }
158
159                 // Trace message
160                 this.getLogger().trace(MessageFormat.format("count={0} - EXIT!", count)); //NOI18N
161
162                 // Return result
163                 return count;
164         }
165
166         /**
167          * Checks whether at least one row is found with given boolean value.
168          *
169          * @param columnName Column to check for boolean value
170          * @param bool Boolean value to check
171          * @return Whether boolean value is found and returns at least one row
172          */
173         @Override
174         public boolean isRowFound (final String columnName, final boolean bool) throws SQLException {
175                 // Is at least one entry found?
176                 if (this.getTotalCount() == 0) {
177                         // No entry found at all
178                         return false;
179                 }
180                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
181         }
182
183         @Override
184         public long length () {
185                 throw new UnsupportedOperationException("Not implemented for this backend."); //NOI18N
186         }
187
188         @Override
189         public void rewind () {
190                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
191         }
192
193         @Override
194         public void store (final Storeable object) throws IOException {
195                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
196         }
197 }