Added SQL List handler and renamed existing handlers

This commit is contained in:
Ziver Koc 2015-12-08 16:29:04 +01:00
parent 432d7cb438
commit 4d60a60c1d
5 changed files with 216 additions and 148 deletions

View file

@ -24,7 +24,7 @@
package zutil.db; package zutil.db;
import zutil.db.handler.SimpleSQLHandler; import zutil.db.handler.SimpleSQLResult;
import zutil.log.LogUtil; import zutil.log.LogUtil;
import javax.naming.InitialContext; import javax.naming.InitialContext;
@ -52,7 +52,7 @@ public class DBConnection implements Closeable{
/** /**
* Creates an Connection from JNDI * Creates an Connection from JNDI
* *
* @param jndi the name of the connection, e.g. "jdbc/mysql" * @param jndi the name of the connection, e.g. "jdbc/mysql"
*/ */
public DBConnection(String jndi) throws NamingException, SQLException{ public DBConnection(String jndi) throws NamingException, SQLException{
InitialContext ctx = new InitialContext(); InitialContext ctx = new InitialContext();
@ -63,10 +63,10 @@ public class DBConnection implements Closeable{
/** /**
* Creates an Connection to a MySQL server * Creates an Connection to a MySQL server
* *
* @param url is the URL of the MySQL server * @param url is the URL of the MySQL server
* @param db is the database to connect to * @param db is the database to connect to
* @param user is the user name * @param user is the user name
* @param password is the password * @param password is the password
*/ */
public DBConnection(String url, String db, String user, String password) throws Exception{ public DBConnection(String url, String db, String user, String password) throws Exception{
this(DBMS.MySQL, url, db, user, password); this(DBMS.MySQL, url, db, user, password);
@ -75,11 +75,11 @@ public class DBConnection implements Closeable{
/** /**
* Creates an Connection to a DB server * Creates an Connection to a DB server
* *
* @param dbms is the DB type * @param dbms is the DB type
* @param url is the URL of the MySQL server * @param url is the URL of the MySQL server
* @param db is the database to connect to * @param db is the database to connect to
* @param user is the user name * @param user is the user name
* @param password is the password * @param password is the password
*/ */
public DBConnection(DBMS dbms, String url, String db, String user, String password) throws Exception{ public DBConnection(DBMS dbms, String url, String db, String user, String password) throws Exception{
String dbms_name = initDriver(dbms); String dbms_name = initDriver(dbms);
@ -89,8 +89,8 @@ public class DBConnection implements Closeable{
/** /**
* Creates an Connection to a DB file * Creates an Connection to a DB file
* *
* @param dbms is the DB type * @param dbms is the DB type
* @param db is the database to connect to * @param db is the database to connect to
*/ */
public DBConnection(DBMS dbms, String db) throws Exception{ public DBConnection(DBMS dbms, String db) throws Exception{
String dbms_name = initDriver(dbms); String dbms_name = initDriver(dbms);
@ -107,7 +107,7 @@ public class DBConnection implements Closeable{
/** /**
* Initiates the DB driver and returns its protocol name. * Initiates the DB driver and returns its protocol name.
* *
* @param db is the DB type * @param db is the DB type
* @return the protocol name of the DBMS * @return the protocol name of the DBMS
*/ */
public String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{ public String initDriver(DBMS db) throws InstantiationException, IllegalAccessException, ClassNotFoundException{
@ -129,7 +129,7 @@ public class DBConnection implements Closeable{
*/ */
public long getLastInsertID(){ public long getLastInsertID(){
try{ try{
return exec("SELECT LAST_INSERT_ID()", new SimpleSQLHandler<BigInteger>()).longValue(); return exec("SELECT LAST_INSERT_ID()", new SimpleSQLResult<BigInteger>()).longValue();
}catch(SQLException e){ }catch(SQLException e){
logger.log(Level.WARNING, null, e); logger.log(Level.WARNING, null, e);
} }
@ -140,7 +140,7 @@ public class DBConnection implements Closeable{
* Runs a Prepared Statement.<br> * Runs a Prepared Statement.<br>
* <b>NOTE:</b> Don't forget to close the PreparedStatement or it can lead to memory leaks * <b>NOTE:</b> Don't forget to close the PreparedStatement or it can lead to memory leaks
* *
* @param sql is the SQL query to run * @param sql is the SQL query to run
* @return An PreparedStatement * @return An PreparedStatement
*/ */
public PreparedStatement getPreparedStatement(String sql) throws SQLException{ public PreparedStatement getPreparedStatement(String sql) throws SQLException{
@ -159,7 +159,7 @@ public class DBConnection implements Closeable{
/** /**
* Executes an query and cleans up after itself. * Executes an query and cleans up after itself.
* *
* @param query is the query * @param query is the query
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
*/ */
public int exec(String query) throws SQLException { public int exec(String query) throws SQLException {
@ -170,7 +170,7 @@ public class DBConnection implements Closeable{
/** /**
* Executes an query and cleans up after itself. * Executes an query and cleans up after itself.
* *
* @param stmt is the query * @param stmt is the query
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
*/ */
public static int exec(PreparedStatement stmt) throws SQLException { public static int exec(PreparedStatement stmt) throws SQLException {
@ -195,10 +195,10 @@ public class DBConnection implements Closeable{
/** /**
* Executes an query and cleans up after itself. * Executes an query and cleans up after itself.
* @param <T> *
* * @param <T>
* @param query is the query * @param query is the query
* @param handler is the result handler * @param handler is the result handler
* @return update count or -1 if the query is not an update query * @return update count or -1 if the query is not an update query
*/ */
public <T> T exec(String query, SQLResultHandler<T> handler) throws SQLException { public <T> T exec(String query, SQLResultHandler<T> handler) throws SQLException {
@ -209,8 +209,8 @@ public class DBConnection implements Closeable{
/** /**
* Executes an query and cleans up after itself. * Executes an query and cleans up after itself.
* *
* @param stmt is the query * @param stmt is the query
* @param handler is the result handler * @param handler is the result handler
* @return the object from the handler * @return the object from the handler
*/ */
public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) throws SQLException{ public static <T> T exec(PreparedStatement stmt, SQLResultHandler<T> handler) throws SQLException{
@ -260,7 +260,7 @@ public class DBConnection implements Closeable{
/** /**
* Sets the pool that this connection belongs to * Sets the pool that this connection belongs to
* *
* @param pool is the pool * @param pool is the pool
*/ */
protected void setPool(DBConnectionPool pool){ protected void setPool(DBConnectionPool pool){
if( pool != null ) if( pool != null )

View file

@ -0,0 +1,68 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Ziver Koc
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package zutil.db.handler;
import zutil.db.SQLResultHandler;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* Adds the result of the query to a List.
*
* The handler will add the first column of every row to a list.
*
* @author Ziver
*/
public class ListSQLResult<T> implements SQLResultHandler<List<T>> {
private List<T> list;
/**
* Creates a new List.
*/
public ListSQLResult(){
this.list = new ArrayList<>();
}
/**
* Uses a existing list that items will be appended on.
*/
public ListSQLResult(List l){
this.list = l;
}
public List<T> handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() )
list.add((T)result.getObject(0));
return list;
}
}

View file

@ -1,69 +1,69 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.db.handler; package zutil.db.handler;
import zutil.db.SQLResultHandler; import zutil.db.SQLResultHandler;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
import java.util.Properties; import java.util.Properties;
/** /**
* Adds the result of the query to a Properties object, * Adds the result of the query to a Properties object,
* *
* The handler sets the first column of the result as * The handler sets the first column of the result as
* the key and the second column as the value * the key and the second column as the value
* *
* @author Ziver * @author Ziver
*/ */
public class PropertiesSQLHandler implements SQLResultHandler<Properties> { public class PropertiesSQLResult implements SQLResultHandler<Properties> {
private Properties prop; private Properties prop;
/** /**
* Creates a new Properties object to be filled * Creates a new Properties object to be filled
*/ */
public PropertiesSQLHandler(){ public PropertiesSQLResult(){
this.prop = new Properties(); this.prop = new Properties();
} }
/** /**
* Adds data to a existing Properties object * Adds data to a existing Properties object
*/ */
public PropertiesSQLHandler(Properties p){ public PropertiesSQLResult(Properties p){
this.prop = p; this.prop = p;
} }
/** /**
* Is called to handle an result from an query. * Is called to handle an result from an query.
*/ */
public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ public Properties handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
while( result.next() ) while( result.next() )
prop.setProperty(result.getString(0), result.getString(1)); prop.setProperty(result.getString(0), result.getString(1));
return prop; return prop;
} }
} }

View file

@ -1,51 +1,51 @@
/* /*
* The MIT License (MIT) * The MIT License (MIT)
* *
* Copyright (c) 2015 Ziver Koc * Copyright (c) 2015 Ziver Koc
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy * Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal * of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights * in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is * copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: * furnished to do so, subject to the following conditions:
* *
* The above copyright notice and this permission notice shall be included in * The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software. * all copies or substantial portions of the Software.
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE. * THE SOFTWARE.
*/ */
package zutil.db.handler; package zutil.db.handler;
import zutil.db.SQLResultHandler; import zutil.db.SQLResultHandler;
import java.sql.ResultSet; import java.sql.ResultSet;
import java.sql.SQLException; import java.sql.SQLException;
import java.sql.Statement; import java.sql.Statement;
/** /**
* Returns the first column of the first row from the query * Returns the first column of the first row from the query
* *
* @author Ziver * @author Ziver
*/ */
public class SimpleSQLHandler<T> implements SQLResultHandler<T> { public class SimpleSQLResult<T> implements SQLResultHandler<T> {
/** /**
* Is called to handle an result from an query. * Is called to handle an result from an query.
* *
* @param stmt is the query * @param stmt is the query
* @param result is the ResultSet * @param result is the ResultSet
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{ public T handleQueryResult(Statement stmt, ResultSet result) throws SQLException{
if( result.next() ) if( result.next() )
return (T) result.getObject(1); return (T) result.getObject(1);
return null; return null;
} }
} }

6
test/zutil/test/DBConnectionTest.java Normal file → Executable file
View file

@ -24,7 +24,7 @@
package zutil.test; package zutil.test;
import zutil.db.DBConnection; import zutil.db.DBConnection;
import zutil.db.handler.SimpleSQLHandler; import zutil.db.handler.SimpleSQLResult;
import java.sql.PreparedStatement; import java.sql.PreparedStatement;
@ -43,13 +43,13 @@ public class DBConnectionTest {
db.exec("UPDATE ..."); db.exec("UPDATE ...");
// Query 3 // Query 3
String s = db.exec("SELECT hello", new SimpleSQLHandler<String>()); String s = db.exec("SELECT hello", new SimpleSQLResult<String>());
System.out.println( s ); System.out.println( s );
// Query 4 // Query 4
PreparedStatement sql2 = db.getPreparedStatement("SELECT ?"); PreparedStatement sql2 = db.getPreparedStatement("SELECT ?");
sql2.setString(1, "hello"); sql2.setString(1, "hello");
String s2 = DBConnection.exec(sql2, new SimpleSQLHandler<String>()); String s2 = DBConnection.exec(sql2, new SimpleSQLResult<String>());
System.out.println( s2 ); System.out.println( s2 );
db.close(); db.close();