]> git.mxchange.org Git - addressbook-swing.git/blob - Addressbook/src/org/mxchange/addressbook/database/backend/mysql/MySqlDatabaseBackend.java
Added text file
[addressbook-swing.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.database.backend.BaseDatabaseBackend;
28 import org.mxchange.addressbook.database.backend.DatabaseBackend;
29 import org.mxchange.addressbook.database.storage.Storeable;
30 import org.mxchange.addressbook.exceptions.BadTokenException;
31 import org.mxchange.addressbook.exceptions.UnsupportedDatabaseDriverException;
32
33 /**
34  * A backend class for MySQL connections
35  *
36  * @author Roland Haeder
37  */
38 public class MySqlDatabaseBackend extends BaseDatabaseBackend implements DatabaseBackend {
39         /**
40          * An instance of a datbase connection
41          */
42         private static Connection connection;
43
44         /**
45          * Prepared statement for full row count
46          */
47         private PreparedStatement totalRowCount;
48
49         /**
50          * Constructor with table name
51          * 
52          * @param tableName Table to access
53          * @throws org.mxchange.addressbook.exceptions.UnsupportedDatabaseDriverException
54          */
55         public MySqlDatabaseBackend (final String tableName) throws UnsupportedDatabaseDriverException {
56                 // Validate driver
57                 this.validateDriver("mysql"); //NOI18N
58
59                 // Now that the driver is there, set the table name
60                 this.setTableName(tableName);
61         }
62
63         @Override
64         public void connectToDatabase () throws SQLException {
65                 // Trace message
66                 this.getLogger().trace("CALLED!"); //NOI18N
67
68                 // Is the connection already there?
69                 if (MySqlDatabaseBackend.connection instanceof Connection) {
70                         // Already connected
71                         this.getLogger().debug("Connection is already established."); //NOI18N
72
73                         // No need to connect
74                         return;
75                 }
76
77                 // Generate connection string
78                 String connect = String.format("jdbc:mysql://%s/%s", //NOI18N
79                                 this.getProperty("database.mysql.host"), //NOI18N
80                                 this.getProperty("database.mysql.dbname") //NOI18N
81                 );
82
83                 // Debug message
84                 this.getLogger().debug(MessageFormat.format("Attempting to connect to {0} ...", connect)); //NOI18N
85
86                 // Now get a connection instance back
87                 MySqlDatabaseBackend.connection = DriverManager.getConnection(
88                                 connect,
89                                 this.getProperty("database.mysql.login"), //NOI18N
90                                 this.getProperty("database.mysql.password") //NOI18N
91                 );
92
93                 // Is the connection really up?
94                 if (MySqlDatabaseBackend.connection.isClosed()) {
95                         // Connection is closed again
96                         throw new SQLException("Connection is closed."); //NOI18N
97                 }
98
99                 // Debug message
100                 this.getLogger().debug("Connection is up, preparing some statements ..."); //NOI18N
101
102                 // Here, the connection is established, so prepare some statements
103                 this.totalRowCount = MySqlDatabaseBackend.connection.prepareStatement(String.format("SELECT COUNT(`id`) AS `cnt` FROM `%s` LIMIT 1", this.getTableName())); //NOI18N
104
105                 // Trace message
106                 this.getLogger().trace("EXIT!"); //NOI18N
107         }
108
109         @Override
110         public void doShutdown () {
111                 // This should not happen:
112                 assert(MySqlDatabaseBackend.connection instanceof Connection) : MessageFormat.format("connection is not valid: {0}", MySqlDatabaseBackend.connection); //NOI18N
113
114                 try {
115                         // Close down database connection
116                         MySqlDatabaseBackend.connection.close();
117                 } catch (final SQLException ex) {
118                         // Something happened during close()
119                         this.abortProgramWithException(ex);
120                 }
121         }
122
123         /**
124          * Some "getter" for row index from given boolean row value
125          *
126          * @param columnName Name of column
127          * @param bool Boolean value to look for
128          * @return Row index
129          */
130         @Override
131         public int getRowIndexFromColumn (final String columnName, final boolean bool) {
132                 throw new UnsupportedOperationException(MessageFormat.format("columnName={0},bool={1}", columnName, bool));
133         }
134
135         @Override
136         public int getTotalCount () throws SQLException {
137                 // Trace message
138                 this.getLogger().trace(MessageFormat.format("tableName={0} - CALLED!", this.getTableName())); //NOI18N
139
140                 // Nothing counted by default
141                 int count = 0;
142
143                 // Prepared statements are cool ...
144                 if (this.totalRowCount.execute()) {
145                         // Did fully work, so get result set
146                         ResultSet set = this.totalRowCount.getResultSet();
147
148                         // First rewind it
149                         assert(set.last()) : ": last() failed"; //NOI18N
150
151                         // Get integer from 'cnt' alias (see statement)
152                         count = set.getInt("cnt"); //NOI18N
153
154                         // Debug message
155                         this.getLogger().debug(MessageFormat.format("count={0}", count)); //NOI18N
156
157                         // Go back to beginning
158                         set.beforeFirst();
159                 } else {
160                         // Empty result
161                         this.getLogger().warn(MessageFormat.format("COUNT() query didn't return any result on table {0}.", this.getTableName())); //NOI18N
162                 }
163
164                 // Trace message
165                 this.getLogger().trace(MessageFormat.format("count={0} - EXIT!", count)); //NOI18N
166
167                 // Return result
168                 return count;
169         }
170
171         /**
172          * Checks whether at least one row is found with given boolean value.
173          *
174          * @param columnName Column to check for boolean value
175          * @param bool Boolean value to check
176          * @return Whether boolean value is found and returns at least one row
177          */
178         @Override
179         public boolean isRowFound (final String columnName, final boolean bool) throws SQLException {
180                 // Is at least one entry found?
181                 if (this.getTotalCount() == 0) {
182                         // No entry found at all
183                         return false;
184                 }
185                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
186         }
187         
188         @Override
189         public Iterator<? extends Storeable> iterator () throws BadTokenException {
190                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
191         }
192
193         @Override
194         public long length () {
195                 throw new UnsupportedOperationException("Not implemented for this backend."); //NOI18N
196         }
197
198         @Override
199         public Storeable readRow (final int rowIndex) {
200                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
201         }
202
203         @Override
204         public void rewind () {
205                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
206         }
207
208         @Override
209         public void store (final Storeable object) throws IOException {
210                 throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
211         }
212 }