Package lazyj
Class DBFunctions
java.lang.Object
lazyj.DBFunctions
- All Implemented Interfaces:
Closeable,AutoCloseable
Wrapper for JDBC connections and collection of useful functions related to database connections. It is also a connection pool, recycling previously established sessions and closing the idle ones.
- Since:
- Oct 15, 2006
- Author:
- costing
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic final classWrapper around a raw database connection. -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final ConcurrentHashMap<String,AtomicInteger> For statistics: how many queries were executed on each connection.static final ConcurrentHashMap<String,AtomicLong> For statistics: total time to execute the queries on each of the connections. -
Constructor Summary
ConstructorsConstructorDescriptionDBFunctions(String driverClass, String jdbcURL) If you already have the full JDBC connection URL, connect like this.DBFunctions(String driverClass, String jdbcURL, Properties configProperties) If you already have the full JDBC connection URL, connect like thisDBFunctions(String driverClass, String jdbcURL, Properties configProperties, String sQuery) If you already have the full JDBC connection URL, connect like this.DBFunctions(Properties configProperties) DBFunctions(Properties configProperties, String sQuery) Create a connection to the database using the parameters in this properties file, then execute the given query.DBFunctions(ExtProperties configProperties) Create a connection to the database using the parameters in this properties file.DBFunctions(ExtProperties configProperties, String sQuery) Create a connection to the database using the parameters in this properties file, then execute the given query. -
Method Summary
Modifier and TypeMethodDescriptionfinal booleanabsolute(int position) Jump to an absolute position in the result setvoidclose()Explicitly close the allocated resourcesstatic StringcomposeInsert(String tableName, Map<String, ?> values) Create an INSERT statement for these valuesstatic StringcomposeUpdate(String tableName, Map<String, ?> values, Collection<String> primaryKeys) Compose an UPDATE SQL statementstatic StringcomposeUpsert(String tableName, Map<String, ?> values, Collection<String> primaryKeys) Build a INSERT-on-conflict-UPDATE queryfinal intcount()Get the number of rows that were selected by the previous query.Given an array in PostgreSQL format, convert it to a Java array of Strings.decodeToInt(String sValue) Convert each entry from an array to Integer.decodeToLong(String sValue) Convert each entry from an array to Long.static StringencodeArray(Collection<?> array) Generate a PostgreSQL array representation of the given one-dimensional collection.protected voidfinalize()Override the default destructor to properly close any resources in use.Statistics : get the number of connections per each unique keystatic final longStatistics : get the number of connections currently establishedfinal booleangetb(int iColumn, boolean bDefault) Get the boolean value of a columnfinal booleanGet the boolean value of a columnfinal byte[]getBytes(int iColumn) Get the raw bytes of this columnfinal byte[]Get the raw bytes of this columnstatic final longStatistics : the total number of closed connection to the databases until now.static final longStatistics : the total number of closed connection to the databases executed when the object is deallocated.final String[]A shortcut to find out the column names for this queryGet the reason why the last connect() attempt has failed.final DBFunctions.DBConnectionGet a raw database connection wrapper.intfinal doublegetd(int iColumn) Get the double value of a column.final doublegetd(int iColumn, double dDefault) Get the double value of a column.final doubleGet the double value of a column.final doubleGet the double value of a column.final DategetDate(int iColumn) Get the column contents converted to Date.final DateGet the value of a column as a Date object.final DateGet the column contents converted to Date.final DateGet the column contents converted to Date.final StringgetEquivalentInsert(String sTable) Get the SQL INSERT statement that would generate the current row with all the columns (their aliases more precisely).final StringgetEquivalentInsert(String sTable, String[] columns) Get the SQL INSERT statement that would generate the current row, for the given list of columnsfinal StringgetEquivalentInsert(String sTable, String[] columns, Map<String, ?> overrides) Get the SQL INSERT statement that would generate the current row, for the given list of columnsfinal floatgetf(int iColumn) Get the float value of a column.final floatgetf(int iColumn, float fDefault) Get the float value of a column.final floatGet the float value of a column.final floatGet the float value of a column.static StringGet the value formatted for SQL statementsfinal intgeti(int iColumn) Get the value of this column as int, returning the default value of 0 if the conversion is not possible.final intgeti(int iColumn, int iDefault) Get the integer value of a column.final intGet the value of this column as int.final intGet the value of this column as int, returning the default value if the conversion is not possible.getIntArray(int iColumn) Extract a PostgreSQL array into a Collection of Integer objectsgetIntArray(String sColumn) Extract a PostgreSQL array into a Collection of Integer objectsfinal longgetl(int iColCount) Get the long value of a column.final longgetl(int iColCount, long lDefault) Get the long value of a column.final longGet the long value of a column.final longGet the long value of a column.Get the last generated key, aftersetLastGeneratedKey(boolean)was called withtrueGet the last generated key, aftersetLastGeneratedKey(boolean)was called withtruefinal ResultSetMetaDataGet the meta information for the current query.getObject(int columnId) Get the content of a column, as native object prepared by the JDBC driverGet the content of a column, as native object prepared by the JDBC driverstatic final longStatistics : the total number of opened connection to the databases until now.final intGet the current position in the result setstatic final longStatistics : get the total number of executed queries.final Stringgets(int iColumn) Get the contents of a column from the current row based on its positionfinal StringGet the contents of a column from the current row based on its position.final StringGet the contents of a column from the current row based on its name.final StringGet the contents of a column from the current row based on its name.getStringArray(int iColumn) Extract a PostgreSQL array into a Collection of String objectsgetStringArray(String sColumn) Extract a PostgreSQL array into a Collection of StriG96Lng objectsintfinal intGet the number of rows affected by the last SQL update query.Convert the result set in a column name -> value mappingbooleanisMySQL()Check if this connection is done to a MySQL database (if we are using the MySQL JDBC driver)booleanCheck if this connection is done to a PostgreSQL database (if we are using the PG JDBC driver)booleanGet the current value of the read-only flagfinal booleanmoveNext()Jump to the next row in the resultstatic final StringpropToJDBC(Properties prop) Build a JDBC URL connection string for a bunch of parametersbooleanExecute a query.final booleanExecute an error and as an option you can force to ignore any errors, no to log them if you expect a query to fail.final booleanrelative(int count) Jump an arbitrary number of rows.intsetCursorType(int type) Set the cursor type to one of the ResultSet.TYPE_FORWARD_ONLY (default), ResultSet.TYPE_SCROLL_INSENSITIVE (when you needcount()or such) and so on.booleansetLastGeneratedKey(boolean enabled) Enable the fetching of the last generated IDfinal intsetQueryTimeout(int newTimeout) Set the query timeout.booleansetReadOnly(boolean readOnly) Signal that the following query is read-only and, if available, a database slave could be used to execute it.voidsetTransactionIsolation(int isolationLevel) Override the transaction isolation level for the following queries.final longsetValidateInterval(long newValidateInterval) Set how often to validate the connection.static final voidStart the cleanup thread.static final voidSignal the thread that it's time to stop.
-
Field Details
-
chmQueryCount
For statistics: how many queries were executed on each connection. -
chmQueryTime
For statistics: total time to execute the queries on each of the connections.
-
-
Constructor Details
-
DBFunctions
Create a connection to the database using the parameters in this properties file. The following keys are extracted:
- driver : (required) one of org.postgresql.Driver, com.mysql.jdbc.Driver or com.microsoft.jdbc.sqlserver.SQLServerDriver
- url : (required) full JDBC URL. If found it would be preferred instead of the following keys (database, host and port)
- database : (required; alternative) name of the database to connect to
- host : (optional) server's ip address, defaults to 127.0.0.1
- port : (optional) tcp port to connect to on the host, if it is missing the default port for each database type is used
- user : (recommended) supply this account name when connecting
- password : (recommended) password for the account
- transactionIsolation : (optional) numerical value of the transaction isolation constant. Default 2 (read committed).
Connection.TRANSACTION_READ_COMMITTED
- MySQL:
- connectTimeout : timeout in milliseconds for a new connection, default is 0 infinite)
- useCompression : true/false, default false
- PostgreSQL:
- ssl : present=true for now
- charSet : string
- Parameters:
configProperties- connection options
-
DBFunctions
- Parameters:
configProperties-- See Also:
-
DBFunctions
Create a connection to the database using the parameters in this properties file, then execute the given query.- Parameters:
configProperties- connection parameterssQuery- query to execute after connecting- See Also:
-
DBFunctions
Create a connection to the database using the parameters in this properties file, then execute the given query.- Parameters:
configProperties- connection parameterssQuery- query to execute after connecting- See Also:
-
DBFunctions
If you already have the full JDBC connection URL, connect like this.- Parameters:
driverClass- JDBC driver class namejdbcURL- JDBC connection URL- See Also:
-
DBFunctions
If you already have the full JDBC connection URL, connect like this- Parameters:
driverClass- JDBC driver class namejdbcURL- full JDBC connection URLconfigProperties- extra configuration options. Can benullif the URL has everything in it- See Also:
-
DBFunctions
If you already have the full JDBC connection URL, connect like this.- Parameters:
driverClass- JDBC driver class namejdbcURL- full JDBC connection URLconfigProperties- extra configuration optionssQuery- query to execute- See Also:
-
-
Method Details
-
setReadOnly
public boolean setReadOnly(boolean readOnly) Signal that the following query is read-only and, if available, a database slave could be used to execute it.- Parameters:
readOnly- iftruethen the query can potentially go to a slave, iffalsethen only the master can execute it- Returns:
- previous value of the read-only flag
-
isReadOnly
public boolean isReadOnly()Get the current value of the read-only flag- Returns:
- read-only flag
-
setCursorType
public int setCursorType(int type) Set the cursor type to one of the ResultSet.TYPE_FORWARD_ONLY (default), ResultSet.TYPE_SCROLL_INSENSITIVE (when you needcount()or such) and so on.- Parameters:
type- new cursor type- Returns:
- previous cursor type
-
getCursorType
public int getCursorType()- Returns:
- cursor type
-
setTransactionIsolation
public void setTransactionIsolation(int isolationLevel) Override the transaction isolation level for the following queries. Set to-1to disable any override.- Parameters:
isolationLevel-
-
getTransactionIsolationLevel
public int getTransactionIsolationLevel()- Returns:
- the override value
-
isPostgreSQL
public boolean isPostgreSQL()Check if this connection is done to a PostgreSQL database (if we are using the PG JDBC driver)- Returns:
- true if the connection is done to a PostgreSQL database
-
isMySQL
public boolean isMySQL()Check if this connection is done to a MySQL database (if we are using the MySQL JDBC driver)- Returns:
- true if the connection is done to a MySQL database
-
getConnectFailReason
Get the reason why the last connect() attempt has failed.- Returns:
- reason, if there is any, or
nullif the connection actually worked
-
getConnection
Get a raw database connection wrapper. Remember to alwaysDBFunctions.DBConnection.free()orDBFunctions.DBConnection.close()at the end of the section where you use it!- Returns:
- database connection wrapper or
nullif a connection cannot be established - See Also:
-
propToJDBC
Build a JDBC URL connection string for a bunch of parameters- Parameters:
prop-- Returns:
- JDBC URL connection string, or
nullif for any reason it cannot be built (unknown driver?)
-
startThread
public static final void startThread()Start the cleanup thread. Should not be called externally since it is called automatically at the first use of this class. -
stopThread
public static final void stopThread()Signal the thread that it's time to stop. You should only call this when the JVM is about to shut down, and not even then it's necessary to do so. -
getUpdateCount
public final int getUpdateCount()Get the number of rows affected by the last SQL update query.- Returns:
- number of rows
-
close
public void close()Explicitly close the allocated resources- Specified by:
closein interfaceAutoCloseable- Specified by:
closein interfaceCloseable
-
finalize
protected void finalize()Override the default destructor to properly close any resources in use. -
query
Execute a query.- Parameters:
sQuery- SQL query to execute- Returns:
trueif the query succeeded,falseif there was an error (connection or syntax).- See Also:
-
setLastGeneratedKey
public boolean setLastGeneratedKey(boolean enabled) Enable the fetching of the last generated ID- Parameters:
enabled- set totrueto be able to do getLastGeneratedKey()- Returns:
- the previous setting
- See Also:
-
getLastGeneratedKey
Get the last generated key, aftersetLastGeneratedKey(boolean)was called withtrue- Returns:
- the last generated key, as Integer, or
nullif there is any problem (orsetLastGeneratedKey(boolean)was not generated) - See Also:
-
getLastGeneratedKeyLong
Get the last generated key, aftersetLastGeneratedKey(boolean)was called withtrue- Returns:
- the last generated key, as Long, or
nullif there is any problem (orsetLastGeneratedKey(boolean)was not generated) - See Also:
-
setQueryTimeout
public final int setQueryTimeout(int newTimeout) Set the query timeout. This is implementation specific, make sure that the JDBC supports it and the functionality is enabled. For MySQL this is done via theenableQueryTimeouts=(default) trueflag.- Parameters:
newTimeout- query timeout, in seconds- Returns:
- old execution timeout
-
setValidateInterval
public final long setValidateInterval(long newValidateInterval) Set how often to validate the connection. The default value is0meaning always check but it can also be overwritten from the properties passed to the constructor with the "validateInterval" key.- Parameters:
newValidateInterval-- Returns:
- old interval to execute isValid()
-
getLastError
- Returns:
- the last known exception
-
query
Execute an error and as an option you can force to ignore any errors, no to log them if you expect a query to fail.- Parameters:
sQuery- query to execute, can be a full query or a prepared statement in which case the values to the columns should be passed as wellbIgnoreErrors-trueif you want to hide any errorsvalues- values to set to the prepared statement- Returns:
- true if the query succeeded, false if there was an error
-
count
public final int count()Get the number of rows that were selected by the previous query. Will only work if you have previously calledsetCursorType(int)with one of the ResultSet.TYPE_SCROLL_* constants.- Returns:
- number of rows, or -1 if the query was not a select one or there was an error
-
getPosition
public final int getPosition()Get the current position in the result set- Returns:
- current position, -1 if there was an error
- See Also:
-
relative
public final boolean relative(int count) Jump an arbitrary number of rows.- Parameters:
count- can be positive or negative- Returns:
- true if the jump was possible, false if not
- See Also:
-
absolute
public final boolean absolute(int position) Jump to an absolute position in the result set- Parameters:
position- new position- Returns:
- true if the positioning was possible, false otherwise
- See Also:
-
moveNext
public final boolean moveNext()Jump to the next row in the result- Returns:
- true if there is a next entry to jump to, false if not
-
gets
Get the contents of a column from the current row based on its name. By default will return "" if there is any problem (column missing, value is null ...)- Parameters:
sColumnName- column name- Returns:
- value, defaulting to ""
- See Also:
-
gets
Get the contents of a column from the current row based on its name. It will return the given default if there is any problem (column missing, value is null ...)- Parameters:
sColumnName- column namesDefault- default value to return if the column doesn't exist or isnull- Returns:
- value for the column with the same name from the current row
- See Also:
-
gets
Get the contents of a column from the current row based on its position- Parameters:
iColumn- column count- Returns:
- value
- See Also:
-
gets
Get the contents of a column from the current row based on its position. It will return the given default if there is any problem (column missing, value is null ...)- Parameters:
iColumn- position (1 = first column of the result set)sDefault- default value to return if the column doesn't exist or isnull- Returns:
- value in the DB or the default value
- See Also:
-
getDate
Get the column contents converted to Date. Will return the given default Date if there is a problem parsing the column.- Parameters:
sColumnName- column name- Returns:
- date, never
nullbut maybe the current time if the contents cannot be converted to Date - See Also:
-
getDate
Get the column contents converted to Date. Will return the given default Date if there is a problem parsing the column.- Parameters:
sColumnName- column namedDefault- default value to return if the contents in db cannot be parsed to Date- Returns:
- date from db, or the default value
- See Also:
-
getDate
Get the column contents converted to Date. Will return the current date/time as default if there is a problem parsing the column.- Parameters:
iColumn- column number ( 1 = first column of the result set )- Returns:
- date from db, or the default value
- See Also:
-
getDate
Get the value of a column as a Date object. Will return the given default Date if there is a problem parsing the column.- Parameters:
iColumn- column number ( 1 = first column of the result set )dDefault- default value to return in case of an error at parsing- Returns:
- a Date representation of this column
- See Also:
-
geti
Get the value of this column as int. Will return the current date/time as default if there is a problem parsing the column.- Parameters:
sColumnName- column- Returns:
- value as int, or 0 if there is a problem parsing
- See Also:
-
geti
Get the value of this column as int, returning the default value if the conversion is not possible.- Parameters:
sColumnName- column nameiDefault- default value to return- Returns:
- the value in the db or the given default if there is a problem parsing
- See Also:
-
geti
public final int geti(int iColumn) Get the value of this column as int, returning the default value of 0 if the conversion is not possible.- Parameters:
iColumn- column position- Returns:
- the value in the db or 0 if there is a problem parsing
- See Also:
-
geti
public final int geti(int iColumn, int iDefault) Get the integer value of a column. Will return the given default value if the column value cannot be parsed into an integer.- Parameters:
iColumn- column numberiDefault- default value to return in case of a parsing error- Returns:
- the integer value of this column
- See Also:
-
getl
Get the long value of a column. Will return 0 by default if the column value cannot be parsed into a long.- Parameters:
sColumnName- column name- Returns:
- the long value of this column
- See Also:
-
getl
Get the long value of a column. Will return the given default value if the column value cannot be parsed into a long.- Parameters:
sColumnName- column namelDefault- default value to return in case of a parsing error- Returns:
- the long value of this column
- See Also:
-
getl
public final long getl(int iColCount) Get the long value of a column. Will return 0 by default if the column value cannot be parsed into a long.- Parameters:
iColCount- column count- Returns:
- the long value of this column
- See Also:
-
getl
public final long getl(int iColCount, long lDefault) Get the long value of a column. Will return the given default value if the column value cannot be parsed into a long.- Parameters:
iColCount- column countlDefault- default value to return in case of a parsing error- Returns:
- the long value of this column
- See Also:
-
getf
Get the float value of a column. Will return 0 by default if the column value cannot be parsed into a float.- Parameters:
sColumnName- column name- Returns:
- the float value of this column
-
getf
Get the float value of a column. Will return the given default value if the column value cannot be parsed into a float.- Parameters:
sColumnName- column namefDefault- default value to return in case of a parsing error- Returns:
- the float value of this column
-
getf
public final float getf(int iColumn) Get the float value of a column. Will return 0 by default if the column value cannot be parsed into a float.- Parameters:
iColumn- column position- Returns:
- the float value of this column
-
getf
public final float getf(int iColumn, float fDefault) Get the float value of a column. Will return the given default value if the column value cannot be parsed into a float.- Parameters:
iColumn- column positionfDefault- default value to return in case of a parsing error- Returns:
- the float value of this column
-
getd
Get the double value of a column. Will return 0 by default if the column value cannot be parsed into a double.- Parameters:
sColumnName- column name- Returns:
- the double value of this column
-
getd
Get the double value of a column. Will return 0 by default if the column value cannot be parsed into a double.- Parameters:
sColumnName- column namedDefault- default value to return in case of a parsing error- Returns:
- the double value of this column
-
getd
public final double getd(int iColumn) Get the double value of a column. Will return 0 by default if the column value cannot be parsed into a double.- Parameters:
iColumn- column position- Returns:
- the double value of this column
-
getd
public final double getd(int iColumn, double dDefault) Get the double value of a column. Will return 0 by default if the column value cannot be parsed into a double.- Parameters:
iColumn- column positiondDefault- default value to return in case of a parsing error- Returns:
- the double value of this column
-
getb
Get the boolean value of a column- Parameters:
sColumn- column namebDefault- default value- Returns:
- true/false, obviously :)
- See Also:
-
getb
public final boolean getb(int iColumn, boolean bDefault) Get the boolean value of a column- Parameters:
iColumn- column indexbDefault- default value- Returns:
- true/false, obviously :)
- See Also:
-
getBytes
public final byte[] getBytes(int iColumn) Get the raw bytes of this column- Parameters:
iColumn-- Returns:
- the bytes of this column
-
getBytes
Get the raw bytes of this column- Parameters:
columnName-- Returns:
- the bytes of this column
-
getStringArray
Extract a PostgreSQL array into a Collection of StriG96Lng objects- Parameters:
sColumn- column name- Returns:
- the values in the array, as Strings
- Since:
- 1.0.3
-
getStringArray
Extract a PostgreSQL array into a Collection of String objects- Parameters:
iColumn- column index- Returns:
- the values in the array, as Strings
- Since:
- 1.0.3
-
getIntArray
Extract a PostgreSQL array into a Collection of Integer objects- Parameters:
sColumn- column name- Returns:
- the values in the array, as Integers
- Since:
- 1.0.3
-
getIntArray
Extract a PostgreSQL array into a Collection of Integer objects- Parameters:
iColumn- column index- Returns:
- the values in the array, as Integers
- Since:
- 1.0.3
-
decodeToInt
Convert each entry from an array to Integer.- Parameters:
sValue-- Returns:
- the members of the database array, as list of Integer objects
- Since:
- 1.0.3
-
decodeToLong
Convert each entry from an array to Long.- Parameters:
sValue-- Returns:
- the members of the database array, as list of Long objects
-
decode
Given an array in PostgreSQL format, convert it to a Java array of Strings.- Parameters:
sValue-- Returns:
- the members of the database array, as list of String objects
- Since:
- 1.0.3
-
encodeArray
Generate a PostgreSQL array representation of the given one-dimensional collection. For details consult the documentation.- Parameters:
array-- Returns:
- a string encoding of the values
- Since:
- 1.0.3
-
getMetaData
Get the meta information for the current query. You can look at this structure to extract column names, types and so on.- Returns:
- the meta information for the current query.
-
getColumnNames
A shortcut to find out the column names for this query- Returns:
- an array of column names
-
getOpenedConnectionsCount
public static final long getOpenedConnectionsCount()Statistics : the total number of opened connection to the databases until now.- Returns:
- total number of opened connections.
-
getClosedConnectionsCount
public static final long getClosedConnectionsCount()Statistics : the total number of closed connection to the databases until now.- Returns:
- total number of closed connections.
-
getClosedOnFinalizeConnectionsCount
public static final long getClosedOnFinalizeConnectionsCount()Statistics : the total number of closed connection to the databases executed when the object is deallocated.- Returns:
- total number of closed connections on object deallocation.
-
getQueryCount
public static final long getQueryCount()Statistics : get the total number of executed queries.- Returns:
- number of executed queries.
-
getActiveConnectionsCount
public static final long getActiveConnectionsCount()Statistics : get the number of connections currently established- Returns:
- the number of active connections
-
getActiveConnections
Statistics : get the number of connections per each unique key- Returns:
- a map of key - number of active connections
-
getEquivalentInsert
Get the SQL INSERT statement that would generate the current row with all the columns (their aliases more precisely).- Parameters:
sTable- table name- Returns:
- the INSERT statement, or
nullif any problem
-
getEquivalentInsert
Get the SQL INSERT statement that would generate the current row, for the given list of columns- Parameters:
sTable- table namecolumns- what column names are to be taken into account- Returns:
- the INSERT statement, or
nullif there was any problem
-
getValuesMap
Convert the result set in a column name -> value mapping- Returns:
- the column name -> value mapping
-
getEquivalentInsert
Get the SQL INSERT statement that would generate the current row, for the given list of columns- Parameters:
sTable- table namecolumns- what column names are to be taken into account. Non-existing column names are ignored.overrides- value overrides. Column names that don't exist in the columns selection are appended to the output.- Returns:
- the INSERT statement, or
nullif there was any problem
-
getFormattedValue
Get the value formatted for SQL statements- Parameters:
o- value to format- Returns:
- formatted string, depending on the object type
-
composeInsert
Create an INSERT statement for these values- Parameters:
tableName- table namevalues- column - value mapping- Returns:
- the SQL statement, or
nullif there was any problem
-
composeUpdate
public static String composeUpdate(String tableName, Map<String, ?> values, Collection<String> primaryKeys) Compose an UPDATE SQL statement- Parameters:
tableName- table namevalues- column - value mappingprimaryKeys- the set of primary keys from the values map- Returns:
- the UPDATE statement
-
composeUpsert
public static String composeUpsert(String tableName, Map<String, ?> values, Collection<String> primaryKeys) Build a INSERT-on-conflict-UPDATE query- Parameters:
tableName-values-primaryKeys-- Returns:
- PostgreSQL-compatible UPSERT command
-
getObject
Get the content of a column, as native object prepared by the JDBC driver- Parameters:
columnId-- Returns:
- the content of the respective column, as an object
-
getObject
Get the content of a column, as native object prepared by the JDBC driver- Parameters:
columnName-- Returns:
- the content of the respective column, as an object
-