下面列出了怎么用java.sql.DatabaseMetaData的API类实例代码及写法,或者点击链接到github查看源代码。
protected void addParentTables(DatabaseMetaData metaData, String schema,
String tableName, String fullTableName) throws SQLException {
HashSet<String> parents = this.parentTables.get(fullTableName);
if (parents == null) {
parents = new HashSet<String>(5);
this.parentTables.put(fullTableName, parents);
}
ResultSet parentRS = metaData.getImportedKeys(null, schema, tableName);
while (parentRS.next()) {
String parentSchema = parentRS.getString("PKTABLE_SCHEM");
String parentTableName = parentRS.getString("PKTABLE_NAME");
parents = this.parentTables.get(fullTableName);
if (parentSchema == null) {
parentSchema = schema;
}
parents.add(parentSchema != null ? parentSchema + '.' + parentTableName
: parentTableName);
}
parentRS.close();
}
/**
* @return list of {@link Columns} we can toggle with suffixes indicating their NOT NULL and default value status
*/
private String constructColumnListWithMetadata() {
try (Connection con = getConnection(mySql)) {
final DatabaseMetaData metaData = con.getMetaData();
final String tableName = settings.getProperty(DatabaseSettings.MYSQL_TABLE);
List<String> formattedColumns = new ArrayList<>(Columns.values().length);
for (Columns col : Columns.values()) {
formattedColumns.add(formatColumnWithMetadata(col, metaData, tableName));
}
return String.join(ChatColor.RESET + ", ", formattedColumns);
} catch (SQLException e) {
logger.logException("Failed to construct column list:", e);
return ChatColor.RED + "An error occurred! Please see the console for details.";
}
}
/**
* Tests fix for BUG#21215151 - DATABASEMETADATA.GETCATALOGS() FAILS TO SORT RESULTS.
*
* DatabaseMetaData.GetCatalogs() relies on the results of 'SHOW DATABASES' which deliver a sorted list of databases except for 'information_schema' which
* is always returned in the first position.
* This test creates set of databases around the relative position of 'information_schema' and checks the ordering of the final ResultSet.
*
* @throws Exception
* if the test fails.
*/
public void testBug21215151() throws Exception {
createDatabase("z_testBug21215151");
createDatabase("j_testBug21215151");
createDatabase("h_testBug21215151");
createDatabase("i_testBug21215151");
createDatabase("a_testBug21215151");
DatabaseMetaData dbmd = this.conn.getMetaData();
this.rs = dbmd.getCatalogs();
System.out.println("Catalogs:");
System.out.println("--------------------------------------------------");
while (this.rs.next()) {
System.out.println("\t" + this.rs.getString(1));
}
this.rs.beforeFirst();
// check the relative position of each element in the result set compared to the previous element.
String previousDb = "";
while (this.rs.next()) {
assertTrue("'" + this.rs.getString(1) + "' is lexicographically lower than the previous catalog. Check the system output to see the catalogs list.",
previousDb.compareTo(this.rs.getString(1)) < 0);
previousDb = this.rs.getString(1);
}
}
public static void getPrimaryKeys(DatabaseMetaData dmd, String tablePattern,PrintStream out)
throws SQLException
{
ResultSet rs = dmd.getPrimaryKeys(null, null, tablePattern);
while (rs.next())
{
// 1.TABLE_CAT String => table catalog (may be null)
String tableCat = rs.getString(1);
// 2.TABLE_SCHEM String => table schema (may be null)
String tableSchem = rs.getString(2);
// 3.TABLE_NAME String => table name
String tableName = rs.getString(3);
// 4.COLUMN_NAME String => column name
String columnName = rs.getString(4);
// 5.KEY_SEQ short => sequence number within primary key
short keySeq = rs.getShort(5);
// 6.PK_NAME String => primary key name (may be null)
String pkName = rs.getString(6);
}
rs.close();
}
static String PARAMTYPE(short type) {
switch (type) {
case DatabaseMetaData.procedureColumnUnknown:
return "procedureColumnUnknown";
case DatabaseMetaData.procedureColumnIn:
return "procedureColumnIn";
case DatabaseMetaData.procedureColumnInOut:
return "procedureColumnInOut";
case DatabaseMetaData.procedureColumnOut:
return "procedureColumnOut";
case DatabaseMetaData.procedureColumnReturn:
return "procedureColumnReturn";
case DatabaseMetaData.procedureColumnResult:
return "procedureColumnResult";
default:
return "???";
}
}
public static void main(String[] args) throws InputException,
InstantiationException, IllegalAccessException, SQLException {
new Activator();
DBSetting setting = new DBSetting("Oracle", "localhost", 1521, "XE",
"nakajima", "nakajima", true, null, null);
Connection con = null;
try {
con = setting.connect();
DatabaseMetaData metaData = con.getMetaData();
metaData.getIndexInfo(null, "SYS", "ALERT_QT", false, false);
} finally {
if (con != null) {
con.close();
}
}
}
/**
* Tests fix for BUG#21978216, GETTYPEINFO REPORT MAXIMUM PRECISION OF 255 FOR VARBINARY
*
* @throws Exception
* if the test fails.
*/
public void testBug21978216() throws Exception {
DatabaseMetaData meta = this.conn.getMetaData();
this.rs = meta.getTypeInfo();
while (this.rs.next()) {
if (this.rs.getString("TYPE_NAME").equals("VARBINARY")) {
if (versionMeetsMinimum(5, 0, 3)) {
assertEquals(65535, this.rs.getInt("PRECISION"));
} else {
assertEquals(255, this.rs.getInt("PRECISION"));
}
}
}
}
public static short getSearchable(Type type) {
/*
* DatabaseMetaData.typePredNone - No support
* DatabaseMetaData.typePredChar - Only support with WHERE .. LIKE
* DatabaseMetaData.typePredBasic - Supported except for WHERE .. LIKE
* DatabaseMetaData.typeSearchable - Supported for all WHERE ..
*/
switch (type) {
case INT1:
case INT2:
case INT4:
case INT8:
case FLOAT4:
case FLOAT8:
case DATE:
case TIME:
case TIMESTAMP:
case NUMERIC: return DatabaseMetaData.typePredBasic;
case VARCHAR:
case TEXT: return DatabaseMetaData.typeSearchable;
default: return DatabaseMetaData.typePredBasic;
}
}
public JethroInfo get(final DatabaseMetaData metaData) {
try {
assert "JethroData".equals(metaData.getDatabaseProductName());
String productVersion = metaData.getDatabaseProductVersion();
synchronized (JethroInfoCacheImpl.this) {
JethroInfo info = map.get(productVersion);
if (info == null) {
final Connection c = metaData.getConnection();
info = makeInfo(c);
map.put(productVersion, info);
}
return info;
}
} catch (Exception e) {
LOGGER.error("Failed to create JethroDataDialect", e);
throw new RuntimeException("Failed to create JethroDataDialect", e);
}
}
static TableSchema from(final Connection conn, final String catalog, final String schema, final String tableName,
final boolean translateColumnNames) throws SQLException {
final DatabaseMetaData dmd = conn.getMetaData();
if (!dmd.getTables(catalog, schema, tableName, null).next()) {
throw new SQLException("Table " + tableName + " does not exist in the database");
}
try (final ResultSet colrs = dmd.getColumns(catalog, schema, tableName, "%")) {
final List<ColumnDescription> cols = new ArrayList<>();
while (colrs.next()) {
final ColumnDescription col = ColumnDescription.from(colrs);
cols.add(col);
}
return new TableSchema(cols, translateColumnNames, dmd.getIdentifierQuoteString());
}
}
@Test
public void testFeatureNotSupportedException() throws Throwable
{
try (Connection connection = getConnection())
{
DatabaseMetaData metaData = connection.getMetaData();
expectFeatureNotSupportedException(() -> metaData.getBestRowIdentifier(
null, null, null, 0, true));
expectFeatureNotSupportedException(() -> metaData.getVersionColumns(null, null, null));
expectFeatureNotSupportedException(() -> metaData.getSuperTypes(null, null, null));
expectFeatureNotSupportedException(() -> metaData.getSuperTables(null, null, null));
expectFeatureNotSupportedException(() -> metaData.getAttributes(null, null, null, null));
expectFeatureNotSupportedException(metaData::getSQLStateType);
expectFeatureNotSupportedException(metaData::locatorsUpdateCopy);
expectFeatureNotSupportedException(metaData::getRowIdLifetime);
expectFeatureNotSupportedException(metaData::autoCommitFailureClosesAllResultSets);
expectFeatureNotSupportedException(metaData::getClientInfoProperties);
expectFeatureNotSupportedException(() -> metaData.getPseudoColumns(null, null, null, null));
expectFeatureNotSupportedException(metaData::generatedKeyAlwaysReturned);
expectFeatureNotSupportedException(() -> metaData.unwrap(SnowflakeDatabaseMetaData.class));
expectFeatureNotSupportedException(() -> metaData.isWrapperFor(SnowflakeDatabaseMetaData.class));
}
}
/**
* Returns true if Oracle Version is >= 12.1 (12.c)
*
* @param connection
* @return true if Oracle Version is >= 12.1 (12.c)
* @throws SQLException
*/
public static boolean isOracleVersionGtOrEq12c(Connection connection)
throws SQLException {
DatabaseMetaData databaseMetaData = connection.getMetaData();
int versionMajor = databaseMetaData.getDatabaseMajorVersion();
int versionMinnor = databaseMetaData.getDatabaseMinorVersion();
if (versionMajor < 12) {
return false;
} else if (versionMajor == 12) {
if (versionMinnor >= 1) {
return true;
} else {
return false;
}
} else {
return true;
}
}
/**
* Check for a ConnectionProxy chain, then delegate to doGetNativeConnection.
* <p>ConnectionProxy is used by Spring's TransactionAwareDataSourceProxy
* and LazyConnectionDataSourceProxy. The target connection behind it is
* typically one from a local connection pool, to be unwrapped by the
* doGetNativeConnection implementation of a concrete subclass.
* @see #doGetNativeConnection
* @see org.springframework.jdbc.datasource.ConnectionProxy
* @see org.springframework.jdbc.datasource.DataSourceUtils#getTargetConnection
* @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
* @see org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy
*/
@Override
public Connection getNativeConnection(Connection con) throws SQLException {
if (con == null) {
return null;
}
Connection targetCon = DataSourceUtils.getTargetConnection(con);
Connection nativeCon = doGetNativeConnection(targetCon);
if (nativeCon == targetCon) {
// We haven't received a different Connection, so we'll assume that there's
// some additional proxying going on. Let's check whether we get something
// different back from the DatabaseMetaData.getConnection() call.
DatabaseMetaData metaData = targetCon.getMetaData();
// The following check is only really there for mock Connections
// which might not carry a DatabaseMetaData instance.
if (metaData != null) {
Connection metaCon = metaData.getConnection();
if (metaCon != null && metaCon != targetCon) {
// We've received a different Connection there:
// Let's retry the native extraction process with it.
nativeCon = doGetNativeConnection(metaCon);
}
}
}
return nativeCon;
}
/**
* Return whether the given JDBC driver supports JDBC 2.0 batch updates.
* <p>Typically invoked right before execution of a given set of statements:
* to decide whether the set of SQL statements should be executed through
* the JDBC 2.0 batch mechanism or simply in a traditional one-by-one fashion.
* <p>Logs a warning if the "supportsBatchUpdates" methods throws an exception
* and simply returns {@code false} in that case.
* @param con the Connection to check
* @return whether JDBC 2.0 batch updates are supported
* @see java.sql.DatabaseMetaData#supportsBatchUpdates()
*/
public static boolean supportsBatchUpdates(Connection con) {
try {
DatabaseMetaData dbmd = con.getMetaData();
if (dbmd != null) {
if (dbmd.supportsBatchUpdates()) {
logger.debug("JDBC driver supports batch updates");
return true;
}
else {
logger.debug("JDBC driver does not support batch updates");
}
}
}
catch (SQLException ex) {
logger.debug("JDBC driver 'supportsBatchUpdates' method threw exception", ex);
}
return false;
}
/**
*
* @param rs
* @param meta
* @param extras
* @throws SQLException
*/
public UKTableMetaData(ResultSet rs, DatabaseMetaData meta, boolean extras, boolean upcase , boolean loadColumns , String dbtype)
throws SQLException {
if(dbtype!=null && dbtype.equals("hive")){
catalog = null;
schema = null;
if(upcase){
name = rs.getObject("tab_name").toString() ;
}else{
name = rs.getObject("tab_name").toString();
}
}else{
catalog = rs.getString("TABLE_CAT");
schema = rs.getString("TABLE_SCHEM");
if(upcase){
name = rs.getString("TABLE_NAME").toUpperCase() ;
}else{
name = rs.getString("TABLE_NAME");
}
}
if(loadColumns){
initColumns(meta , upcase);
}
}
private ResultSet doFunctions(Session session, Connection con, Options options)
throws SQLException {
if (options.arguments.size() > 2) {
session.err.println("Use: \\show functions [[[catalog.]schema-pattern.]func-pattern]");
return null;
}
if (options.essential) {
options.columns = essentialFunctionCols;
}
SQLConnectionContext ctx = (SQLConnectionContext) session.getConnectionContext();
SQLObjectName name =
(options.arguments.size() == 2) ? new SQLObjectName(ctx, options.arguments.get(1))
: new SQLObjectName(ctx, "%");
DatabaseMetaData meta = con.getMetaData();
return meta.getFunctions(
(options.catalog != null ? options.catalog : name.getCatalog()),
(options.schemaPattern != null ? options.schemaPattern : name.getSchema()),
(options.tablePattern != null ? options.tablePattern : name.getName()));
}
public static void getPrimaryKeys(DatabaseMetaData dmd, String tablePattern,PrintStream out)
throws SQLException
{
ResultSet rs = dmd.getPrimaryKeys(null, null, tablePattern);
while (rs.next())
{
// 1.TABLE_CAT String => table catalog (may be null)
String tableCat = rs.getString(1);
// 2.TABLE_SCHEM String => table schema (may be null)
String tableSchem = rs.getString(2);
// 3.TABLE_NAME String => table name
String tableName = rs.getString(3);
// 4.COLUMN_NAME String => column name
String columnName = rs.getString(4);
// 5.KEY_SEQ short => sequence number within primary key
short keySeq = rs.getShort(5);
// 6.PK_NAME String => primary key name (may be null)
String pkName = rs.getString(6);
}
rs.close();
}
/**
* Return whether the given JDBC driver supports JDBC 2.0 batch updates.
* <p>Typically invoked right before execution of a given set of statements:
* to decide whether the set of SQL statements should be executed through
* the JDBC 2.0 batch mechanism or simply in a traditional one-by-one fashion.
* <p>Logs a warning if the "supportsBatchUpdates" methods throws an exception
* and simply returns {@code false} in that case.
* @param con the Connection to check
* @return whether JDBC 2.0 batch updates are supported
* @see java.sql.DatabaseMetaData#supportsBatchUpdates()
*/
public static boolean supportsBatchUpdates(Connection con) {
try {
DatabaseMetaData dbmd = con.getMetaData();
if (dbmd != null) {
if (dbmd.supportsBatchUpdates()) {
logger.debug("JDBC driver supports batch updates");
return true;
}
else {
logger.debug("JDBC driver does not support batch updates");
}
}
}
catch (SQLException ex) {
logger.debug("JDBC driver 'supportsBatchUpdates' method threw exception", ex);
}
return false;
}
/**
* 返回就诶过 key:column name , value=index name
*/
public static Map<String/* column name */, String /* index name */> getTableIndex(final DataSource dataSource,
final String schemaName,
final String tableName) {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return (Map<String, String>) jdbcTemplate.execute(new ConnectionCallback() {
public Object doInConnection(Connection conn) throws SQLException, DataAccessException {
DatabaseMetaData metaData = conn.getMetaData();
String sName = getIdentifierName(schemaName, metaData);
String tName = getIdentifierName(tableName, metaData);
ResultSet rs = metaData.getIndexInfo(sName, sName, tName, false, true);
Map<String, String> indexes = new HashMap<String, String>();
while (rs.next()) {
String columnName = rs.getString(9);
String indexName = rs.getString(6);
if (columnName != null && indexName != null) {
indexes.put(columnName, indexName);
}
}
rs.close();
return indexes;
}
});
}
protected Schema inferSchemaResultSet(JDBCTableMetadata tableMetadata) throws SQLException {
DatabaseMetaData databaseMetdata = tableMetadata.getDatabaseMetaData();
Set<String> keys = getPrimaryKeys(databaseMetdata, tableMetadata.getCatalog(), tableMetadata.getDbSchema(),
tableMetadata.getTablename());
Set<String> existNames = new HashSet<String>();
int index = 0;
try (ResultSet metadata = databaseMetdata.getColumns(tableMetadata.getCatalog(), tableMetadata.getDbSchema(),
tableMetadata.getTablename(), null)) {
if (!metadata.next()) {
return null;
}
List<Field> fields = new ArrayList<>();
String tablename = metadata.getString("TABLE_NAME");
do {
int size = metadata.getInt("COLUMN_SIZE");
int scale = metadata.getInt("DECIMAL_DIGITS");
int dbtype = metadata.getInt("DATA_TYPE");
boolean nullable = DatabaseMetaData.columnNullable == metadata.getInt("NULLABLE");
String columnName = metadata.getString("COLUMN_NAME");
boolean isKey = keys.contains(columnName);
String defaultValue = metadata.getString("COLUMN_DEF");
String validName = NameUtil.correct(columnName, index++, existNames);
existNames.add(validName);
Field field = sqlType2Avro(size, scale, dbtype, nullable, validName, columnName, defaultValue, isKey);
fields.add(field);
} while (metadata.next());
return Schema.createRecord(NameUtil.correct(tablename, 0, new HashSet<String>()), null, null, false, fields);
}
}
private void createJobExecutionTableAndIndexIfNeeded(final Connection connection) throws SQLException {
DatabaseMetaData dbMetaData = connection.getMetaData();
try (ResultSet resultSet = dbMetaData.getTables(connection.getCatalog(), null, TABLE_JOB_EXECUTION_LOG, new String[]{"TABLE"})) {
if (!resultSet.next()) {
createJobExecutionTable(connection);
}
}
}
private void execute(Connection con, int schemaVersion) throws Exception
{
final DatabaseMetaData dbmd = con.getMetaData();
String schemaName = databaseMetaDataHelper.getSchema(con);
schema = new Schema(schemaName, namePrefix, schemaVersion, true);
String[] prefixFilters = namePrefixFilters(dbmd);
for (String filter : prefixFilters)
{
extractSchema(dbmd, schemaName, filter);
}
}
@Override
public Pair<TableDesc, TableExtDesc> loadTableMetadata(String database, String table, String prj)
throws SQLException {
TableDesc tableDesc = new TableDesc();
tableDesc.setDatabase(database.toUpperCase(Locale.ROOT));
tableDesc.setName(table.toUpperCase(Locale.ROOT));
tableDesc.setUuid(RandomUtil.randomUUID().toString());
tableDesc.setLastModified(0);
tableDesc.setSourceType(ISourceAware.ID_JDBC);
Connection con = SqlUtil.getConnection(dbconf);
DatabaseMetaData dbmd = con.getMetaData();
try (ResultSet rs = jdbcMetadataDialect.getTable(dbmd, database, table)) {
String tableType = null;
while (rs.next()) {
tableType = rs.getString("TABLE_TYPE");
}
if (tableType != null) {
tableDesc.setTableType(tableType);
} else {
throw new RuntimeException(
String.format(Locale.ROOT, "table %s not found in schema:%s", table, database));
}
}
try (ResultSet rs = jdbcMetadataDialect.listColumns(dbmd, database, table)) {
tableDesc.setColumns(extractColumnFromMeta(rs));
} finally {
DBUtils.closeQuietly(con);
}
TableExtDesc tableExtDesc = new TableExtDesc();
tableExtDesc.setIdentity(tableDesc.getIdentity());
tableExtDesc.setUuid(RandomUtil.randomUUID().toString());
tableExtDesc.setLastModified(0);
tableExtDesc.init(prj);
return Pair.newPair(tableDesc, tableExtDesc);
}
@Test
public void testDatabaseMetaDataMethodsThrowRight() {
NoNonSqlExceptionsChecker<DatabaseMetaData> checker =
new NoNonSqlExceptionsChecker<>(DatabaseMetaData.class,
databaseMetaData);
checker.testMethods();
if (checker.hadAnyFailures()) {
fail("Non-SQLException exception error(s): \n" + checker.getReport());
}
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
this.checkState();
DatabaseMetaData metaData = null;
try {
metaData = this.connection.getMetaData();
} catch (SQLException ex) {
this.handleException(ex);
}
DatabaseMetaData metaDataProxy = ProxyFactory.createProxyDatabaseMetaData(this, metaData);
return metaDataProxy;
}
@Test
public void testExistingTransactionWithManualSavepoint() throws Exception {
DatabaseMetaData md = mock(DatabaseMetaData.class);
Savepoint sp = mock(Savepoint.class);
given(md.supportsSavepoints()).willReturn(true);
given(con.getMetaData()).willReturn(md);
given(con.setSavepoint("SAVEPOINT_1")).willReturn(sp);
final TransactionTemplate tt = new TransactionTemplate(tm);
tt.setPropagationBehavior(TransactionDefinition.PROPAGATION_NESTED);
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
assertTrue("Synchronization not active", !TransactionSynchronizationManager.isSynchronizationActive());
tt.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) throws RuntimeException {
assertTrue("Is new transaction", status.isNewTransaction());
Object savepoint = status.createSavepoint();
status.releaseSavepoint(savepoint);
assertTrue("Is new transaction", status.isNewTransaction());
}
});
assertTrue("Hasn't thread connection", !TransactionSynchronizationManager.hasResource(ds));
verify(con).releaseSavepoint(sp);
verify(con).commit();
verify(con).close();
verify(ds).getConnection();
}
/**
* @param fireSchemaInfoUpdate Should only be false when the caller makes sure fireSchemaInfoUpdate() is called later.
*/
void refreshCacheForSimpleProcedureName(String simpleProcName, boolean fireSchemaInfoUpdate)
{
HashMap<String, String> caseSensitiveProcNames = new HashMap<String, String>();
CaseInsensitiveString caseInsensitiveProcName = new CaseInsensitiveString(simpleProcName);
String caseSensitiveProcName = _schemaInfoCache.getProcedureNamesForReadOnly().remove(caseInsensitiveProcName);
caseSensitiveProcNames.put(caseSensitiveProcName, caseSensitiveProcName);
////////////////////////////////////////////////////////////////////////
// Reload all matching procedure types
for(Iterator<String> i=caseSensitiveProcNames.keySet().iterator(); i.hasNext();)
{
String buf = i.next();
ProcedureInfo pi = new ProcedureInfo(null, null, buf, null, DatabaseMetaData.procedureResultUnknown, _dmd);
reload(pi, fireSchemaInfoUpdate);
}
//
////////////////////////////////////////////////////////////////////////
// is done in reload
// if(fireSchemaInfoUpdate)
// {
// fireSchemaInfoUpdate();
// }
}
protected static Map getIndexes(String table_name, DatabaseMetaData dbm) throws SQLException {
// returns { table_name(colname,...) : index_name }
Map result = new HashMap(5);
ResultSet rs = dbm.getIndexInfo(null, null, table_name, false, false);
String prev_index_name = null;
String columns = null;
while (rs.next()) {
String index_name = rs.getString(6);
if (prev_index_name != null && !prev_index_name.equals(index_name)) {
result.put(table_name + '(' + columns + ')', prev_index_name);
columns = null;
}
// column_name might be quoted, so unquote it before proceeding
String column_name = unquote(rs.getString(9), dbm.getIdentifierQuoteString());
if (columns == null)
columns = column_name;
else
columns = columns + "," + column_name;
prev_index_name = index_name;
}
rs.close();
if (prev_index_name != null)
result.put(table_name + '(' + columns + ')', prev_index_name);
return result;
}
/**
* Insert Operation.
*/
private void addInsertOperation(DataService dataServiceObject,
String schema, DatabaseMetaData metaData, String dbName,
String tableName) throws DataServiceFault, SQLException {
ResultSet columnNames = null;
/* do insertion operation */
try {
Map<String, WithParam> paramMap = new HashMap<String, WithParam>();
List<String> paramList = new ArrayList<String>();
columnNames = getColumnNames(metaData, schema, dbName, tableName, null);
while (columnNames.next()) {
if (this.isAutoIncrementField(columnNames)) {
continue;
}
String name = columnNames.getString(DBConstants.DataServiceGenerator.COLUMN_NAME);
WithParam withParam = new WithParam(name, name, name, DBConstants.DataServiceGenerator.QUERY_PARAM);
paramMap.put(name, withParam);
paramList.add(name);
}
Set<String> requiredRoles = new HashSet<String>();
String queryId = DBConstants.DataServiceGenerator.INSERT_ + tableName + DBConstants.DataServiceGenerator._QUERY;
String OpName = DBConstants.DataServiceGenerator.INSERT_ + tableName + DBConstants.DataServiceGenerator._OPERATION;
CallQuery callQuery = new CallQuery(dataServiceObject, queryId,
paramMap, requiredRoles);
// batchRequest=false
// parentOperation=null
Operation op = new Operation(dataServiceObject, OpName, null,
callQuery, false, null, false, false);
dataServiceObject.addOperation(op);
dataServiceObject.addQuery(this.getInsertQuery(paramList, queryId,
tableName, dataServiceObject, metaData, dbName, schema));
} finally {
if (columnNames != null) {
columnNames.close();
}
}
}
/**
* Export data base contents to a directory using supplied connection.
*
* @param connection database connection
* @param directory target directory
* @throws Exception
*/
public void process(Connection connection, String directory) throws Exception
{
connection.setAutoCommit(true);
//
// Retrieve meta data about the connection
//
DatabaseMetaData dmd = connection.getMetaData();
String[] types =
{
"TABLE"
};
FileWriter fw = new FileWriter(directory);
PrintWriter pw = new PrintWriter(fw);
pw.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
pw.println();
pw.println("<database>");
ResultSet tables = dmd.getTables(null, null, null, types);
while (tables.next() == true)
{
processTable(pw, connection, tables.getString("TABLE_NAME"));
}
pw.println("</database>");
pw.close();
tables.close();
}