public abstract class Database extends Object
Database d=new OracleDatabase("user","password");
for(String food : d.query("SELECT foodname FROM food", ResultIterator.StringWrapper)) {
System.out.print(food);
}
-> Pizza Spaghetti Saltimbocca
It is possible to execute multiple INSERT statements by a bulk loader:
d=new OracleDatabase(...); Database.Inserter i=d.newInserter(tableName); i.insert(7,"Hallo"); i.insert(8,"Ciao"); ... i.close();The inserters are automatically flushed every 1000 insertions and when closed. They are flushed and closed when the database is closed.
Unfortunately, the same datatype is called differently on different database
systems, behaves differently and is written down differently. There is an
ANSI standard, but of course nobody cares. This is why Database.java provides
a method getSQLType(int), which takes any of the SQL datatypes defined in
java.sql.Types (e.g. VARCHAR) and returns an object of the class
javatools.SQLType. This object then behaves according to the conventions of
the respective database system. Each implementation of Database.java should
return SQLType-objects tailored to the specific database (e.g. OracleDatabase
maps BOOLEAN to NUMBER(1) and replaces quotes in string literals by double
quotes). By default, the ANSI datatypes are returned.
Example:
Database d=new OracleDatabase("user","password");
d.getSQLType(java.sql.Types.VARCHAR).format("Bobby's")
-> 'Bobby"s'
d=new MySQLDatabase("user","password","database");
d.getSQLType(java.sql.Types.VARCHAR).format("Bobby's")
-> 'Bobby\'s'
Technical issues: Implementations of Database.java can extend the ANSI type
classes given in SQLType.java and they can modify the maps java2SQL and
type2SQL provided by Database.java. See OracleDatabase.java for an example.
For each datatype class, there should only be one instance (per scale).
Unfortunately, Java does not allow instances to have different method
implementation, so that each datatype has to be a class. It would be
convenient to handle datatypes as enums, but enums cannot be extended. To
facilitate modifying the ANSI types for subclasses, the getSQLType-method is
non-static. Implementations of this class should have a noarg-constructor to
enable calls to getSQLType without establishing a database connection.| Modifier and Type | Class and Description |
|---|---|
static class |
Database.CommitTransactionSQLException |
static class |
Database.ConnectionBrokenSQLException
Exceptions ****
|
static class |
Database.InitTransactionSQLException |
class |
Database.Inserter
Represents a bulk loader
|
static class |
Database.RollbackTransactionSQLException |
static class |
Database.StartAutoCommitSQLException |
static class |
Database.TransactionSQLException |
| Modifier and Type | Field and Description |
|---|---|
protected Connection |
connection
Handle for the database
|
protected String |
description
/** Describes this database
|
protected Driver |
driver
The Driver registered for this database instance
TODO: it may be more reasonable to share the same driver instance for all database insances
of the same type...check that and adapt
|
protected int |
fetchsize
The fetchsize to be used on default, i.e.
|
protected List<Database.Inserter> |
inserters
Holds all active inserters to close them in the end
|
Map<Class<?>,SQLType> |
java2SQL
The mapping from Java to SQL
|
static int |
MINCOLUMNWIDTH
The minal column width for describe()
|
protected int |
resultSetConcurrency
The concurrency type of the resultSet (read only by default)
|
protected int |
resultSetType
The type of the resultSet (Forward only by default)
|
static int |
SCREENWIDTH
The screen width for describe()
|
Map<Integer,SQLType> |
type2SQL
The mapping from type codes (as defined in java.sql.Types) to SQL
|
| Constructor and Description |
|---|
Database() |
| Modifier and Type | Method and Description |
|---|---|
protected static void |
appendFixedLen(StringBuilder b,
Object o,
int len)
Appends something to a StringBuilder with a fixed length
|
protected void |
attemptReconnect(SQLException cause,
boolean autoReconnect)
called when query execution failed due to some exception;
checks connectivity and if connection is broken may attempt to reconnect
depending on the given parameters,
if the connection is still alive, reconnection fails or
autoReconnect is not enabled throws a fitting exception
|
String |
autoincrementColumn()
Produces an SQL fragment representing an autoincrementing column type
s.t.
|
String |
cast(String value,
String type)
Produces an SQL fragment casting the given value to the given type *
|
void |
close()
Closes the connection
|
static void |
close(Connection connection)
Closes a connection
|
static void |
close(ResultSet rs)
Closes a result set
|
static void |
close(Statement statement)
Closes a statement
|
protected void |
commitTransaction()
commits the transaction aggregated so far
if the commit fails the transaction is rolled back!
|
abstract void |
connect()
connects to the database specified
|
boolean |
connected()
Checks whether the connection to the database is still alive
|
void |
createIndex(String table,
boolean unique,
String... attributes) |
String |
createIndexCommand(String table,
boolean unique,
String... attributes)
Returns the command to create one index on a table
|
void |
createIndices(String table,
String... attributes)
Creates non-unique single indices on a table
|
void |
createPrimaryKey(String table,
String... attributes)
makes the given attributes/columns the primary key of the given table
|
void |
createTable(String name,
Object... attributes)
Creates or rewrites an SQL table.
|
void |
createView(String name,
String query)
creates a view with given name over the query
|
static String |
describe(ResultSet r)
Returns a String-representation of a ResultSet
|
static String |
describe(ResultSet r,
int maxrows)
Returns a String-representation of a ResultSet, maximally maxrows rows (or
all for -1)
|
void |
dumpCSV(String table,
File output,
char separator)
Produces a CSV version of the table
|
void |
dumpQueryAsCSV(String selectCommand,
File output,
char separator)
Produces a CSV version of the query
|
void |
endTransaction()
executes the transaction and switches back from transaction mode into autocommit mode
|
void |
endTransaction(boolean flush)
Deprecated.
|
protected ResultSet |
executeQuery(String sql,
int resultSetType,
int resultSetConcurrency,
Integer fetchsize)
Returns the results for a query as a ResultSet with given type, concurrency and
fetchsize.
|
int |
executeUpdate(CharSequence sqlcs)
Executes an SQL update query, returns the number of rows added/deleted
|
protected int |
executeUpdateQuery(String sqlcs)
Executes an SQL update query, returns the number of rows added/deleted
|
boolean |
exists(CharSequence sql)
Returns TRUE if the resultset is not empty
|
boolean |
existsTable(String table)
checks if a table with the given name exists (or rather whether it can be accessed).
|
void |
finalize()
Closes the connection
|
void |
flush()
Flush the connection
|
String |
format(Object o)
Formats an object appropriately (provided that its class is in java2SQL)
|
String |
formatNullToNull(Object o)
Formats an object appropriately (provided that its class is in java2SQL)
and assigns NULL if the given object is a null pointer
|
Connection |
getConnection()
Returns the connection
|
int |
getFetchsize()
gets the current default fetchsize affecting all queries
where no specific fetchsize is provided as query argument
The fetchsize determines how many result rows are pulled in from the server at once.
|
int |
getResultSetConcurrency()
Returns the resultSetConcurrency
|
int |
getResultSetType()
Returns the resultSetType
|
String |
getSQLStmntIFNULL(String a,
String b)
returns the database system specific expression for if-null functionality
i.e.
|
SQLType |
getSQLType(Class<?> c)
Returns an SQLType for the given class
|
SQLType |
getSQLType(int t)
Returns an SQLType for the given Type as defined in java.sql.Types
|
SQLType |
getSQLType(int t,
int scale)
Returns an SQLType for the given Type as defined in java.sql.Types with a
scale
|
int |
getValidityCheckTimeout()
time in milliseconds after which a connection is considered broken
when no answer is received within that time frame
|
String |
indexName(String table,
String... attributes)
Creates an index name
|
boolean |
isAutoReconnectingOnSelect()
indicates whether automatic reconnection and requerying is attempted
when a broken connection is discovered after an informative (SELECT) query
if this is set to false, a ConnectionBrokenSQLException is thrown instead
|
boolean |
isAutoReconnectingOnUpdate()
indicates whether automatic reconnection and requerying is attempted
when a broken connection is discovered after an update (INSERT, UPDATE) query
if this is set to false, a ConnectionBrokenSQLException is thrown instead
Note: In rare cases this may lead to an update query being executed twice,
so treat with care!
|
boolean |
jarAvailable()
TRUE if the required JAR is there
|
String |
limit(String sql,
int n)
Makes an SQL query limited to n results
|
void |
loadCSV(String table,
File input,
boolean clearTable,
char separator)
Loads a CSV file into a table
|
void |
lockTableReadAccess(Map<String,String> tableAndAliases)
Locks a table in read mode, i.e.
|
void |
lockTableWriteAccess(Map<String,String> tableAndAliases)
Locks a table in write mode, i.e.
|
static void |
main(String[] args)
Test routine
|
void |
makeCSV(String table,
File output,
char separator)
Produces a CSV version of the table
|
void |
makeCSVForQuery(String selectCommand,
File output,
char separator)
Produces a CSV version of the query
|
Database.Inserter |
newInserter(String table)
Returns an inserter for a table with specific column types
|
Database.Inserter |
newInserter(String table,
Class<?>... argumentTypes)
Returns an inserter for a table with specific column types
|
Database.Inserter |
newInserter(String table,
int... argumentTypes)
Returns an inserter for a table with specific column types given as java.sql.Type constants
|
String |
offset(String sql,
int n)
Makes sure a query response starts at the n-th result
|
protected String |
prepareQuery(String sql)
Prepares the query internally for a call (e.g.
|
ResultSet |
query(CharSequence sql)
Returns the results for a query as a ResultSet with default type and
concurrency (read comments!).
|
ResultSet |
query(CharSequence sqlcs,
int resultSetType,
int resultSetConcurrency)
Returns the results for a query as a ResultSet with given type and
concurrency.
|
ResultSet |
query(CharSequence sqlcs,
int resultSetType,
int resultSetConcurrency,
Integer fetchsize)
Returns the results for a query as a ResultSet with given type, concurrency and
fetchsize.
|
<T> ResultIterator<T> |
query(CharSequence sql,
ResultIterator.ResultWrapper<T> rc)
Returns the results for a query as a ResultIterator
|
<T> T |
queryValue(CharSequence sql,
ResultIterator.ResultWrapper<T> rc)
Returns a single value (or null)
|
void |
reconnect()
(re-)connects to the database specified
|
void |
releaseLocksAndEndTransaction()
releases all locks the connection holds, commits the current transaction and ends it
|
void |
resetTransaction()
resets the transaction rolling it back and closing it
|
void |
runInterface()
Runs a user-interface and closes
|
void |
setAutoReconnectOnSelect(boolean autoReconnectOnSelect)
enable/disable automatic reconnection and requerying
when a broken connection is discovered after an informative (SELECT) query
if this is set to false, a ConnectionBrokenSQLException is thrown instead
|
void |
setAutoReconnectOnUpdate(boolean autoReconnectOnUpdate)
enables/disables whether automatic reconnection and requerying is attempted
when a broken connection is discovered after an update (INSERT, UPDATE) query
if this is set to false, a ConnectionBrokenSQLException is thrown instead
Note: In rare cases this may lead to an update query being executed twice,
so treat with care!
|
void |
setFetchsize(int fetchsize)
sets the default fetchsize affecting all following queries
where no specific fetchsize is provided as query argument
The fetchsize determines how many result rows are pulled in from the server at once.
|
void |
setResultSetConcurrency(int resultSetConcurrency)
Sets the resultSetConcurrency
|
void |
setResultSetType(int resultSetType)
Sets the resultSetType
|
void |
setValidityCheckTimeout(int validityCheckTimeout)
sets the amount of time a database has to answer to a connection probing
before the connection is considered broken
Note: the value cannot be smaller than 0
|
void |
startTransaction()
Initiates a transaction by disabling autocommit and enabling transaction mode
|
String |
toString()
Misc.
|
protected Connection connection
protected String description
protected int resultSetType
protected int resultSetConcurrency
protected int fetchsize
protected Driver driver
protected List<Database.Inserter> inserters
public Map<Integer,SQLType> type2SQL
public static final int MINCOLUMNWIDTH
public static final int SCREENWIDTH
public Connection getConnection()
public void reconnect()
throws SQLException
SQLExceptionpublic abstract void connect()
throws SQLException
SQLExceptionpublic static void close(Connection connection)
public static void close(Statement statement)
public static void close(ResultSet rs)
public void close()
public void flush()
throws SQLException
SQLExceptionpublic boolean jarAvailable()
public boolean isAutoReconnectingOnSelect()
public void setAutoReconnectOnSelect(boolean autoReconnectOnSelect)
public boolean isAutoReconnectingOnUpdate()
public void setAutoReconnectOnUpdate(boolean autoReconnectOnUpdate)
public int getFetchsize()
public void setFetchsize(int fetchsize)
public int getValidityCheckTimeout()
public void setValidityCheckTimeout(int validityCheckTimeout)
protected String prepareQuery(String sql)
public int getResultSetConcurrency()
public void setResultSetConcurrency(int resultSetConcurrency)
public int getResultSetType()
public void setResultSetType(int resultSetType)
public boolean connected()
protected void attemptReconnect(SQLException cause, boolean autoReconnect) throws SQLException
SQLExceptionprotected ResultSet executeQuery(String sql, int resultSetType, int resultSetConcurrency, Integer fetchsize) throws SQLException
SQLExceptionpublic ResultSet query(CharSequence sqlcs, int resultSetType, int resultSetConcurrency, Integer fetchsize) throws SQLException
SQLExceptionpublic ResultSet query(CharSequence sqlcs, int resultSetType, int resultSetConcurrency) throws SQLException
SQLExceptionpublic ResultSet query(CharSequence sql) throws SQLException
SQLExceptionpublic int executeUpdate(CharSequence sqlcs) throws SQLException
SQLExceptionprotected int executeUpdateQuery(String sqlcs) throws SQLException
SQLExceptionpublic <T> ResultIterator<T> query(CharSequence sql, ResultIterator.ResultWrapper<T> rc) throws SQLException
SQLExceptionpublic <T> T queryValue(CharSequence sql, ResultIterator.ResultWrapper<T> rc) throws SQLException
SQLExceptionpublic boolean exists(CharSequence sql) throws SQLException
SQLExceptionpublic void startTransaction()
throws Database.InitTransactionSQLException
protected void commitTransaction()
throws Database.TransactionSQLException
Database.TransactionSQLExceptionpublic void resetTransaction()
throws Database.TransactionSQLException
Database.TransactionSQLExceptionpublic void endTransaction()
throws Database.TransactionSQLException
Database.TransactionSQLException@Deprecated public void endTransaction(@Deprecated boolean flush) throws Database.TransactionSQLException
flush - deprecated, will be removed
Note: The flush parameter is deprecated and will be removed as the transaction end always requires a commitDatabase.TransactionSQLExceptionpublic void lockTableWriteAccess(Map<String,String> tableAndAliases) throws SQLException
SQLExceptionpublic void lockTableReadAccess(Map<String,String> tableAndAliases) throws SQLException
SQLExceptionpublic void releaseLocksAndEndTransaction()
throws SQLException
SQLExceptionprotected static void appendFixedLen(StringBuilder b, Object o, int len)
public static String describe(ResultSet r, int maxrows) throws SQLException
SQLExceptionpublic static String describe(ResultSet r) throws SQLException
SQLExceptionpublic SQLType getSQLType(int t)
public SQLType getSQLType(int t, int scale)
public String getSQLStmntIFNULL(String a, String b)
public String format(Object o)
public String formatNullToNull(Object o)
public String cast(String value, String type)
public String offset(String sql, int n)
public String autoincrementColumn()
public void createTable(String name, Object... attributes) throws SQLException
SQLExceptionpublic boolean existsTable(String table)
table - name of the table to be checked
Note: if there is any error with the database connection,
the function will also return false.public String createIndexCommand(String table, boolean unique, String... attributes)
public void createIndex(String table, boolean unique, String... attributes) throws SQLException
SQLExceptionpublic void createIndices(String table, String... attributes) throws SQLException
SQLExceptionpublic void createPrimaryKey(String table, String... attributes) throws SQLException
SQLExceptionpublic void createView(String name, String query) throws SQLException
SQLExceptionpublic void makeCSV(String table, File output, char separator) throws IOException, SQLException
IOExceptionSQLExceptionpublic void dumpCSV(String table, File output, char separator) throws IOException, SQLException
IOExceptionSQLExceptionpublic void makeCSVForQuery(String selectCommand, File output, char separator) throws IOException, SQLException
IOExceptionSQLExceptionpublic void dumpQueryAsCSV(String selectCommand, File output, char separator) throws IOException, SQLException
IOExceptionSQLExceptionpublic void loadCSV(String table, File input, boolean clearTable, char separator) throws IOException, SQLException
IOExceptionSQLExceptionpublic void runInterface()
public Database.Inserter newInserter(String table) throws SQLException
SQLExceptionpublic Database.Inserter newInserter(String table, Class<?>... argumentTypes) throws SQLException
SQLExceptionpublic Database.Inserter newInserter(String table, int... argumentTypes) throws SQLException
SQLExceptionCopyright © 2018. All rights reserved.