Java Code Examples for java.sql.DatabaseMetaData

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project Karaf-Tutorial, under directory /db/command/src/main/java/net/lr/tutorial/karaf/db/service/.

Source file: DbAccess.java

  23 
vote

public ShellTable getTableInfo() throws Exception {
  if (dataSource == null) {
    throw new RuntimeException("No DataSource selected");
  }
  Connection con=dataSource.getConnection();
  DatabaseMetaData metaData=con.getMetaData();
  ResultSet rs=metaData.getTables(null,null,null,null);
  ShellTable table=printResult(rs);
  rs.close();
  return table;
}
 

Example 2

From project arastreju, under directory /arastreju.rdb/src/main/java/org/arastreju/bindings/rdb/jdbc/.

Source file: DBOperations.java

  22 
vote

public static boolean tableExists(Connection con,String name){
  try {
    DatabaseMetaData meta=con.getMetaData();
    return meta.getTables(null,null,name,null).next();
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
  return false;
}
 

Example 3

From project bonecp, under directory /bonecp/src/main/java/com/jolbox/bonecp/.

Source file: ConnectionHandle.java

  22 
vote

public DatabaseMetaData getMetaData() throws SQLException {
  DatabaseMetaData result=null;
  checkClosed();
  try {
    result=this.connection.getMetaData();
  }
 catch (  SQLException e) {
    throw markPossiblyBroken(e);
  }
  return result;
}
 

Example 4

From project CIShell, under directory /clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/.

Source file: DatabaseSchemaOverviewGenerator.java

  22 
vote

private static List<String> getTableNames(Connection dbConnection,String defaultSchemaName) throws SQLException {
  DatabaseMetaData dbMetadata=dbConnection.getMetaData();
  ResultSet allTableNames=dbMetadata.getTables(null,defaultSchemaName,null,null);
  List<String> nonSystemTableNames=new ArrayList<String>();
  while (allTableNames.next()) {
    String schemaName=allTableNames.getString("TABLE_SCHEM");
    if (isNonSystemSchemaName(schemaName,defaultSchemaName)) {
      String tableName=allTableNames.getString("TABLE_NAME");
      nonSystemTableNames.add(tableName);
    }
  }
  return nonSystemTableNames;
}
 

Example 5

From project Citizens, under directory /src/core/net/citizensnpcs/properties/db/.

Source file: DatabaseStorage.java

  22 
vote

public boolean columnExists(String table,String column){
  if (aliases.containsKey(table))   table=aliases.get(table);
  try {
    this.ensureConnection();
    DatabaseMetaData meta=connection.getMetaData();
    ResultSet rs=meta.getColumns(null,null,table,column);
    return rs.next();
  }
 catch (  SQLException ex) {
    throw new RuntimeException(ex);
  }
}
 

Example 6

From project codjo-data-process, under directory /codjo-data-process-server/src/main/java/net/codjo/dataprocess/server/util/.

Source file: DatabaseTools.java

  22 
vote

private static String getLegalTables(Connection connection) throws SQLException {
  StringBuilder tableList=new StringBuilder(",");
  DatabaseMetaData metaData=connection.getMetaData();
  ResultSet tables=metaData.getTables(null,null,null,new String[]{"TABLE","VIEW"});
  try {
    while (tables.next()) {
      tableList.append(tables.getString("TABLE_NAME")).append(",");
    }
  }
  finally {
    tables.close();
  }
  return tableList.toString();
}
 

Example 7

From project codjo-imports, under directory /codjo-imports-common/src/main/java/net/codjo/imports/common/.

Source file: SQLFieldList.java

  22 
vote

/** 
 * Construction d'une liste de champs a partir de la definition de la table pour un catalogue donn.
 * @param dbTableName Le nom physique de la table.
 * @param con         La connection.
 * @param catalog     Le catalogue de la table.
 * @throws SQLException Erreur d'access a la base.
 */
SQLFieldList(String dbTableName,Connection con,String catalog) throws SQLException {
  DatabaseMetaData md=con.getMetaData();
  ResultSet rs=md.getColumns(catalog,null,dbTableName,null);
  while (rs.next()) {
    String dbFieldName=rs.getString(4);
    int sqlType=rs.getInt(5);
    addField(dbFieldName,sqlType);
  }
}
 

Example 8

From project codjo-standalone-common, under directory /src/main/java/net/codjo/utils/.

Source file: SQLFieldList.java

  22 
vote

/** 
 * Construction d'une liste de champs a partir de la definition de la table pour un catalogue donn.
 * @param dbTableName Le nom physique de la table.
 * @param con La connection.
 * @param catalog Le catalogue de la table.
 * @exception SQLException Erreur d'access a la base.
 */
public SQLFieldList(String dbTableName,Connection con,String catalog) throws SQLException {
  DatabaseMetaData md=con.getMetaData();
  ResultSet rs=md.getColumns(catalog,null,dbTableName,null);
  while (rs.next()) {
    String dbFieldName=rs.getString(4);
    int sqlType=rs.getInt(5);
    addField(dbFieldName,sqlType);
  }
}
 

Example 9

From project flyway, under directory /flyway-core/src/main/java/com/googlecode/flyway/core/dbsupport/.

Source file: DbSupportFactory.java

  22 
vote

/** 
 * Retrieves the name of the database product.
 * @param connection The connection to use to query the database.
 * @return The name of the database product. Ex.: Oracle, MySQL, ...
 */
private static String getDatabaseProductName(Connection connection){
  try {
    DatabaseMetaData databaseMetaData=connection.getMetaData();
    if (databaseMetaData == null) {
      throw new FlywayException("Unable to read database metadata while it is null!");
    }
    return databaseMetaData.getDatabaseProductName();
  }
 catch (  SQLException e) {
    throw new FlywayException("Error while determining database product name",e);
  }
}
 

Example 10

From project gxa, under directory /atlas-web/src/main/java/uk/ac/ebi/gxa/jmx/.

Source file: AtlasManager.java

  22 
vote

public String getDataSourceURL(){
  String result;
  try {
    Connection c=DataSourceUtils.getConnection(dataSource);
    DatabaseMetaData dmd=c.getMetaData();
    result=dmd.getUserName() + " @ " + dmd.getURL();
    DataSourceUtils.releaseConnection(c,dataSource);
    return result;
  }
 catch (  SQLException e) {
    throw LogUtil.createUnexpected("Unable to obtain connection to the datasource, or failed to read URL");
  }
}
 

Example 11

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/cache/eager/.

Source file: EagerDatabaseMetaDataCache.java

  22 
vote

private DatabaseProperties createDatabaseProperties(Connection connection) throws SQLException {
  DatabaseMetaData metaData=connection.getMetaData();
  Dialect dialect=this.cluster.getDialect();
  DatabaseMetaDataSupport support=this.factory.createSupport(metaData,dialect);
  return new EagerDatabaseProperties(metaData,support,dialect);
}
 

Example 12

From project hiho, under directory /src/co/nubetech/apache/hadoop/.

Source file: DBInputFormat.java

  22 
vote

/** 
 * {@inheritDoc} 
 */
public void setConf(Configuration conf){
  dbConf=new DBConfiguration(conf);
  try {
    getConnection();
    DatabaseMetaData dbMeta=connection.getMetaData();
    this.dbProductName=dbMeta.getDatabaseProductName().toUpperCase();
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
  tableName=dbConf.getInputTableName();
  fieldNames=dbConf.getInputFieldNames();
  conditions=dbConf.getInputConditions();
}
 

Example 13

From project iciql, under directory /src/com/iciql/.

Source file: Db.java

  22 
vote

private Db(Connection conn){
  this.conn=conn;
  String databaseName=null;
  DatabaseMetaData data=null;
  try {
    data=conn.getMetaData();
    databaseName=data.getDatabaseProductName();
  }
 catch (  SQLException s) {
    throw new IciqlException(s,"failed to retrieve database metadata!");
  }
  dialect=getDialect(databaseName,conn.getClass().getName());
  dialect.configureDialect(databaseName,data);
}
 

Example 14

From project james, under directory /util/src/main/java/org/apache/james/util/bayesian/.

Source file: JDBCBayesianAnalyzer.java

  22 
vote

private void checkTables(Connection conn) throws SQLException {
  DatabaseMetaData dbMetaData=conn.getMetaData();
  boolean dbUpdated=false;
  dbUpdated=createTable(conn,"hamTableName","createHamTable");
  dbUpdated=createTable(conn,"spamTableName","createSpamTable");
  dbUpdated=createTable(conn,"messageCountsTableName","createMessageCountsTable");
  if (conn != null && dbUpdated && !conn.getAutoCommit()) {
    conn.commit();
    dbUpdated=false;
  }
}
 

Example 15

From project liquibase, under directory /liquibase-core/src/test/java/liquibase/.

Source file: LiquibaseTest.java

  22 
vote

@Before public void setUp() throws Exception {
  if (connectionForConstructor != null) {
    reset(connectionForConstructor);
  }
  connectionForConstructor=createMock(DatabaseConnection.class);
  connectionForConstructor.setAutoCommit(false);
  expectLastCall().atLeastOnce();
  DatabaseMetaData metaData=createMock(DatabaseMetaData.class);
  expect(metaData.getDatabaseProductName()).andReturn("Oracle");
  replay(metaData);
  replay(connectionForConstructor);
  testLiquibase=new TestLiquibase();
}
 

Example 16

From project rapid, under directory /rapid-generator/rapid-generator/src/main/java/cn/org/rapid_framework/generator/provider/db/table/.

Source file: TableFactory.java

  22 
vote

private List<Table> getAllTables() throws SQLException {
  DatabaseMetaData dbMetaData=connection.getMetaData();
  ResultSet rs=dbMetaData.getTables(getCatalog(),getSchema(),null,null);
  try {
    List<Table> tables=new ArrayList<Table>();
    while (rs.next()) {
      tables.add(createTable(rs));
    }
    return tables;
  }
  finally {
    DBHelper.close(rs);
  }
}
 

Example 17

From project riot, under directory /revolt/src/org/riotfamily/revolt/support/.

Source file: DatabaseUtils.java

  22 
vote

/** 
 * Returns the JDBC-URL for the given DataSource.
 */
public static String getUrl(DataSource dataSource){
  JdbcTemplate template=new JdbcTemplate(dataSource);
  return (String)template.execute(new ConnectionCallback(){
    public Object doInConnection(    Connection connection) throws SQLException, DataAccessException {
      DatabaseMetaData metaData=connection.getMetaData();
      return metaData.getURL();
    }
  }
);
}
 

Example 18

From project spring-insight-plugins, under directory /collection-plugins/jdbc/src/test/java/com/springsource/insight/plugin/jdbc/.

Source file: JdbcDriverConnectOperationCollectionAspectTest.java

  22 
vote

private Operation runConnectionTest() throws SQLException {
  Connection conn=connectDriver.connect(connectUrl,connectProps);
  try {
    DatabaseMetaData metaData=conn.getMetaData();
    String connURL=metaData.getURL();
    assertEquals("Mismatched meta-data URL(s)",connectUrl,connURL);
    assertTrackedConnection(conn,connURL);
  }
  finally {
    conn.close();
    assertConnectionNotTracked(conn);
  }
  return assertConnectDetails(connectDriver,connectUrl,connectProps);
}
 

Example 19

From project sqoop, under directory /src/java/org/apache/sqoop/mapreduce/db/.

Source file: DBInputFormat.java

  22 
vote

@Override public void setConf(Configuration conf){
  dbConf=new DBConfiguration(conf);
  try {
    getConnection();
    DatabaseMetaData dbMeta=connection.getMetaData();
    this.dbProductName=dbMeta.getDatabaseProductName().toUpperCase();
  }
 catch (  Exception ex) {
    throw new RuntimeException(ex);
  }
  tableName=dbConf.getInputTableName();
  fieldNames=dbConf.getInputFieldNames();
  conditions=dbConf.getInputConditions();
}
 

Example 20

From project tedis, under directory /tedis-replicator/src/main/java/com/taobao/common/tedis/replicator/database/.

Source file: MySQLDatabase.java

  22 
vote

public ArrayList<String> getSchemas() throws SQLException {
  ArrayList<String> schemas=new ArrayList<String>();
  try {
    DatabaseMetaData md=this.getDatabaseMetaData();
    ResultSet rs=md.getCatalogs();
    while (rs.next()) {
      schemas.add(rs.getString("TABLE_CAT"));
    }
    rs.close();
  }
  finally {
  }
  return schemas;
}
 

Example 21

From project Weave, under directory /JTDS_SqlServerDriver/src/test/net/sourceforge/jtds/test/.

Source file: DatabaseMetaDataJDBC3Test.java

  22 
vote

/** 
 * Test meta data functions that return boolean values.
 */
public void testBooleanOptions() throws Exception {
  DatabaseMetaData dbmd=con.getMetaData();
  assertTrue("locatorsUpdateCopy",dbmd.locatorsUpdateCopy());
  assertTrue("supportsGetGeneratedKeys",dbmd.supportsGetGeneratedKeys());
  assertTrue("supportsMultipleOpenResults",dbmd.supportsMultipleOpenResults());
  assertTrue("supportsNamedParameters",dbmd.supportsNamedParameters());
  assertFalse("supportsResultSetHoldability",dbmd.supportsResultSetHoldability(ResultSet.HOLD_CURSORS_OVER_COMMIT));
  assertFalse("supportsResultSetHoldability",dbmd.supportsResultSetHoldability(ResultSet.CLOSE_CURSORS_AT_COMMIT));
  assertTrue("supportsSavepoints",dbmd.supportsSavepoints());
  assertTrue("supportsStatementPooling",dbmd.supportsStatementPooling());
}
 

Example 22

From project Web-Karma-Public, under directory /src/main/java/edu/isi/karma/util/.

Source file: MySQLUtil.java

  22 
vote

@Override public ArrayList<String> getListOfTables(Connection conn) throws SQLException, ClassNotFoundException {
  ArrayList<String> tableNames=new ArrayList<String>();
  DatabaseMetaData dmd=conn.getMetaData();
  ResultSet rs=dmd.getTables(null,null,null,new String[]{"TABLE"});
  while (rs.next())   tableNames.add(rs.getString(3));
  Collections.sort(tableNames);
  return tableNames;
}
 

Example 23

From project AdminCmd, under directory /src/main/java/lib/SQL/PatPeter/SQLibrary/.

Source file: Database.java

  21 
vote

/** 
 * <b>checkTable</b><br> <br> &nbsp;&nbsp;Checks a table in a database based on the table's name. <br> <br>
 * @param table - name of the table to check.
 * @return success of the method.
 */
public boolean checkTable(final String table){
  DatabaseMetaData dbm=null;
  try {
synchronized (connection) {
      dbm=this.connection.getMetaData();
    }
    final ResultSet tables=dbm.getTables(null,null,table,null);
    if (tables.next()) {
      return true;
    }
 else {
      return false;
    }
  }
 catch (  final SQLException e) {
    this.writeError("Failed to check if table \"" + table + "\" exists: "+ e.getMessage(),true);
    return false;
  }
}
 

Example 24

From project ANNIS, under directory /annis-service/src/main/java/annis/dao/.

Source file: SpringAnnisDao.java

  21 
vote

@Override public boolean checkDatabaseVersion() throws AnnisException {
  Connection conn=null;
  try {
    conn=getJdbcTemplate().getDataSource().getConnection();
    DatabaseMetaData meta=conn.getMetaData();
    log.info("major: " + meta.getDatabaseMajorVersion() + " minor: "+ meta.getDatabaseMinorVersion()+ " complete: "+ meta.getDatabaseProductVersion()+ " name: "+ meta.getDatabaseProductName());
  }
 catch (  SQLException ex) {
    log.error("could not get database version",ex);
  }
 finally {
    if (conn != null) {
      try {
        conn.close();
      }
 catch (      SQLException ex) {
        log.error(null,ex);
      }
    }
  }
  return false;
}
 

Example 25

From project core_5, under directory /exo.core.component.database/src/main/java/org/exoplatform/services/database/.

Source file: ExoDatasource.java

  21 
vote

/** 
 * The constructor should: 1. Keep track of the datasource object 2. Create the DBTableManager object base on the datasource information such database type, version 3. Create an IDGenerator for the datasource
 * @param ds
 * @throws Exception
 */
public ExoDatasource(final DataSource ds) throws Exception {
  xaDatasource_=ds;
  DatabaseMetaData metaData=SecurityHelper.doPrivilegedSQLExceptionAction(new PrivilegedExceptionAction<DatabaseMetaData>(){
    public DatabaseMetaData run() throws SQLException {
      return ds.getConnection().getMetaData();
    }
  }
);
  databaseName_=metaData.getDatabaseProductName();
  databaseVersion_=metaData.getDatabaseProductVersion();
  String dbname=databaseName_.toLowerCase();
  LOG.debug("DB Name: " + dbname);
  if (dbname.indexOf("oracle") >= 0) {
    dbType_=ORACLE_DB_TYPE;
  }
 else   if (dbname.indexOf("hsql") >= 0) {
    dbType_=HSQL_DB_TYPE;
  }
 else   if (dbname.indexOf("mysql") >= 0) {
    dbType_=MYSQL_DB_TYPE;
  }
 else   if (dbname.indexOf("derby") >= 0) {
    dbType_=DERBY_DB_TYPE;
  }
 else   if (dbname.indexOf("db2") >= 0) {
    dbType_=DB2_DB_TYPE;
  }
 else   if (dbname.indexOf("server") >= 0) {
    dbType_=SQL_SERVER_TYPE;
  }
 else {
    dbType_=STANDARD_DB_TYPE;
  }
  tableManager_=DBTableManager.createDBTableManager(this);
  idGenerator_=new IDGenerator(this);
  queryManager_=new QueryBuilder(dbType_);
}
 

Example 26

From project DB-Builder, under directory /src/main/java/org/silverpeas/dbbuilder/sql/.

Source file: ConnectionFactory.java

  21 
vote

public static String getConnectionInfo() throws SQLException {
  StringBuilder builder=new StringBuilder();
  Connection connection=null;
  try {
    connection=getConnection();
    DatabaseMetaData metaData=connection.getMetaData();
    String newLine=System.getProperty("line.separator");
    builder.append(newLine).append("\tRDBMS         : ").append(metaData.getDatabaseProductName());
    builder.append(newLine).append("\tJdbcUrl       : ").append(metaData.getURL());
    builder.append(newLine).append("\tJdbcDriver    : ").append(metaData.getDriverName());
    builder.append(newLine).append("\tUserName      : ").append(metaData.getUserName());
  }
  finally {
    if (connection != null) {
      connection.close();
    }
  }
  return builder.toString();
}
 

Example 27

From project db2triples, under directory /src/main/java/net/antidot/sql/model/core/.

Source file: SQLConnector.java

  21 
vote

/** 
 * Drop all tables from database with connection c. Specific to MySQL databases.
 * @param c
 * @param driver 
 * @throws SQLException
 */
public static void resetMySQLDatabase(Connection c,DriverType driver) throws SQLException {
  DatabaseMetaData meta=c.getMetaData();
  ResultSet tablesSet=meta.getTables(c.getCatalog(),null,"%",null);
  while (tablesSet.next()) {
    String tableName=new String(tablesSet.getString("TABLE_NAME"));
    String tableType=tablesSet.getString("TABLE_TYPE");
    Statement stmt=c.createStatement();
    if (driver == DriverType.MysqlDriver) {
      stmt.execute("SET FOREIGN_KEY_CHECKS = 0");
      stmt.execute("DROP TABLE \"" + tableName + "\"");
    }
 else {
      if (tableType != null && tableType.equals("TABLE"))       stmt.execute("DROP TABLE \"" + tableName + "\" CASCADE");
    }
    stmt.close();
  }
}
 

Example 28

From project empire-db, under directory /empire-db/src/test/java/org/apache/empire/db/.

Source file: IntegerTest.java

  21 
vote

private List<String> getTableNames(DBDatabase db,Connection conn){
  List<String> tables=new ArrayList<String>();
  ResultSet result=null;
  try {
    DatabaseMetaData metaData=conn.getMetaData();
    result=metaData.getTables(db.getSchema(),null,null,null);
    while (result.next()) {
      tables.add(result.getString("TABLE_NAME"));
    }
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
 finally {
    if (result != null) {
      try {
        result.close();
      }
 catch (      SQLException e) {
        e.printStackTrace();
      }
    }
  }
  return tables;
}
 

Example 29

From project galaxy, under directory /src/co/paralleluniverse/galaxy/jdbc/.

Source file: SQLDB.java

  21 
vote

private void initDbTypes() throws SQLException {
  if (bigintType == null || smallintType == null || varbinaryType == null) {
    final Map<Integer,String> types=new HashMap<Integer,String>();
    final DatabaseMetaData dmd=conn.getMetaData();
    final ResultSet rs=dmd.getTypeInfo();
    while (rs.next()) {
      final int jdbcType=rs.getInt("DATA_TYPE");
      final String typeName=rs.getString("TYPE_NAME");
      types.put(jdbcType,typeName);
    }
    rs.close();
    if (bigintType == null)     bigintType=types.get(Types.BIGINT);
    if (smallintType == null)     smallintType=types.get(Types.SMALLINT);
    if (varbinaryType == null)     varbinaryType=types.get(Types.VARBINARY);
    LOG.debug("BIGINT type is: {}",bigintType);
    LOG.debug("SMALLINT type is: {}",smallintType);
    LOG.debug("VARBINARY type is: {}",varbinaryType);
  }
}
 

Example 30

From project gemini-dbaccess, under directory /samples/org.eclipse.gemini.dbaccess.samples/src/org/eclipse/gemini/dbaccess/samples/.

Source file: DataSourceClientExample.java

  21 
vote

void useEmbeddedDataSource(DataSourceFactory dsf){
  Properties props=new Properties();
  props.put(DataSourceFactory.JDBC_URL,"jdbc:derby:testDB;create=true");
  DataSource ds=null;
  Connection conn=null;
  try {
    ds=dsf.createDataSource(props);
    conn=ds.getConnection();
    DatabaseMetaData metadata=conn.getMetaData();
    log("Driver accessed by sample Gemini DBAccess client:" + "\n\tName = " + metadata.getDriverName() + "\n\tVersion = "+ metadata.getDriverVersion()+ "\n\tUser = "+ metadata.getUserName());
    conn.close();
  }
 catch (  SQLException sqlEx) {
    log("Sample Gemini DBAccess client - Error creating or using data source: " + sqlEx);
  }
}
 

Example 31

From project gemini.dbaccess, under directory /samples/org.eclipse.gemini.dbaccess.samples/src/org/eclipse/gemini/dbaccess/samples/.

Source file: DataSourceClientExample.java

  21 
vote

void useEmbeddedDataSource(DataSourceFactory dsf){
  Properties props=new Properties();
  props.put(DataSourceFactory.JDBC_URL,"jdbc:derby:testDB;create=true");
  DataSource ds=null;
  Connection conn=null;
  try {
    ds=dsf.createDataSource(props);
    conn=ds.getConnection();
    DatabaseMetaData metadata=conn.getMetaData();
    log("Driver accessed by sample Gemini DBAccess client:" + "\n\tName = " + metadata.getDriverName() + "\n\tVersion = "+ metadata.getDriverVersion()+ "\n\tUser = "+ metadata.getUserName());
    conn.close();
  }
 catch (  SQLException sqlEx) {
    log("Sample Gemini DBAccess client - Error creating or using data source: " + sqlEx);
  }
}
 

Example 32

From project guj.com.br, under directory /src/net/jforum/dao/.

Source file: MySQLVersionWorkarounder.java

  21 
vote

public void handleWorkarounds(Connection c){
  if (c == null) {
    logger.warn("Cannot work with a null connection");
    return;
  }
  if (!"mysql".equals(SystemGlobals.getValue(ConfigKeys.DATABASE_DRIVER_NAME))) {
    return;
  }
  try {
    DatabaseMetaData meta=c.getMetaData();
    logger.debug("MySQL Version: " + meta.getDatabaseProductVersion());
    int major=meta.getDatabaseMajorVersion();
    int minor=meta.getDatabaseMinorVersion();
    if (major == 3 && minor == 23) {
      this.handleMySql323();
    }
 else     if (major == 4 && minor == 0) {
      this.handleMySql40x();
    }
 else     if (major > 4 || (major == 4 && minor > 0)) {
      this.handleMySql41xPlus();
    }
  }
 catch (  Exception e) {
    logger.error(e.toString(),e);
  }
}
 

Example 33

From project jdonframework, under directory /src/com/jdon/util/.

Source file: DbUtil.java

  21 
vote

public static void testConnection(Connection con){
  if (init)   return;
  init=true;
  streamLargeText=false;
  supportsMaxRows=true;
  supportsFetchSize=true;
  try {
    DatabaseMetaData metaData=con.getMetaData();
    String dbName=metaData.getDatabaseProductName().toLowerCase();
    String driverName=metaData.getDriverName().toLowerCase();
    if (dbName.indexOf(ORACLE) != -1) {
      streamLargeText=true;
      if (driverName.indexOf("auguro") != -1) {
        streamLargeText=false;
        supportsFetchSize=true;
        supportsMaxRows=false;
      }
    }
 else     if (dbName.indexOf(POSTGRES) != -1) {
      supportsFetchSize=false;
    }
 else     if (dbName.indexOf(INTERBASE) != -1) {
      supportsFetchSize=false;
      supportsMaxRows=false;
    }
 else     if (dbName.indexOf(SQLSERVER) != -1 && driverName.indexOf("una") != -1) {
      supportsFetchSize=true;
      supportsMaxRows=false;
    }
 else     if (dbName.indexOf(MYSQL) != -1) {
    }
  }
 catch (  Exception ex) {
  }
}
 

Example 34

From project jforum2, under directory /src/net/jforum/dao/.

Source file: MySQLVersionWorkarounder.java

  21 
vote

public void handleWorkarounds(Connection c){
  if (c == null) {
    logger.warn("Cannot work with a null connection");
    return;
  }
  if (!"mysql".equals(SystemGlobals.getValue(ConfigKeys.DATABASE_DRIVER_NAME))) {
    return;
  }
  try {
    DatabaseMetaData meta=c.getMetaData();
    logger.debug("MySQL Version: " + meta.getDatabaseProductVersion());
    int major=meta.getDatabaseMajorVersion();
    int minor=meta.getDatabaseMinorVersion();
    if (major == 3 && minor == 23) {
      this.handleMySql323();
    }
 else     if (major == 4 && minor == 0) {
      this.handleMySql40x();
    }
 else     if (major > 4 || (major == 4 && minor > 0)) {
      this.handleMySql41xPlus();
    }
  }
 catch (  Exception e) {
    logger.error(e.toString(),e);
  }
}
 

Example 35

From project jibu, under directory /jibu-core/src/main/java/org/gaixie/jibu/security/dao/.

Source file: SchemaCreate.java

  21 
vote

/** 
 * ??? dbscripts ????????? type????????????????????????? sql ??????? <p>
 * @param type ????????????? jibu.properties ????????
 */
public void create(String type){
  Connection conn=null;
  try {
    conn=ConnectionUtils.getConnection();
    DatabaseMetaData dbm=conn.getMetaData();
    ResultSet rs=dbm.getTables(null,null,"USERBASE",null);
    if (rs.next())     throw new SQLException("Schema has been created!");
    String dpn=dbm.getDatabaseProductName();
    if (!"Apache Derby".equals(dpn))     throw new SQLException("Database is not Apache Derby!");
    QueryRunner run=new QueryRunner();
    URL url=this.getClass().getResource("/dbscripts/" + type + "/");
    File dir=new File(url.toURI());
    File[] files=dir.listFiles();
    Arrays.sort(files);
    for (    File file : files) {
      if (file.isFile()) {
        handleFile(run,conn,"/dbscripts/" + type + "/"+ file.getName());
      }
    }
    DbUtils.commitAndClose(conn);
  }
 catch (  SQLException se) {
    DbUtils.rollbackAndCloseQuietly(conn);
    logger.warn("Schema create failed: " + se.getMessage());
  }
catch (  IOException ie) {
    DbUtils.rollbackAndCloseQuietly(conn);
    logger.warn("Read SQL Scripts failed: " + ie.getMessage());
  }
catch (  URISyntaxException e) {
    DbUtils.rollbackAndCloseQuietly(conn);
    logger.warn("Get SQL Scripts Directory failed: " + e.getMessage());
  }
}
 

Example 36

From project logback, under directory /logback-core/src/main/java/ch/qos/logback/core/db/.

Source file: ConnectionSourceBase.java

  21 
vote

/** 
 * Learn relevant information about this connection source.
 */
public void discoverConnectionProperties(){
  try {
    Connection connection=getConnection();
    if (connection == null) {
      addWarn("Could not get a connection");
      return;
    }
    DatabaseMetaData meta=connection.getMetaData();
    DBUtil util=new DBUtil();
    util.setContext(getContext());
    supportsGetGeneratedKeys=util.supportsGetGeneratedKeys(meta);
    supportsBatchUpdates=util.supportsBatchUpdates(meta);
    dialectCode=DBUtil.discoverSQLDialect(meta);
    addInfo("Driver name=" + meta.getDriverName());
    addInfo("Driver version=" + meta.getDriverVersion());
    addInfo("supportsGetGeneratedKeys=" + supportsGetGeneratedKeys);
  }
 catch (  SQLException se) {
    addWarn("Could not discover the dialect to use.",se);
  }
}
 

Example 37

From project myberkeley, under directory /provision/src/main/java/edu/berkeley/myberkeley/provision/.

Source file: OracleConnectionService.java

  21 
vote

@Activate @Modified protected void activate(ComponentContext componentContext){
  Dictionary<?,?> props=componentContext.getProperties();
  LOGGER.info("New props = {}",props);
  dataSourceUrl=PropertiesUtil.toString(props.get(DATASOURCE_URL),null);
  Connection testConnection=null;
  try {
    dataSource=new OracleDataSource();
    dataSource.setURL(dataSourceUrl);
    testConnection=getConnection();
    DatabaseMetaData meta=testConnection.getMetaData();
    LOGGER.info("JDBC driver version is " + meta.getDriverVersion());
  }
 catch (  SQLException e) {
    LOGGER.error(e.getMessage(),e);
    deactivate(componentContext);
    throw new ComponentException("Could not get test connection");
  }
 finally {
    if (testConnection != null) {
      try {
        testConnection.close();
      }
 catch (      SQLException e) {
        LOGGER.error("Failed on final connection close",e);
      }
    }
  }
}
 

Example 38

From project nuxeo-services, under directory /nuxeo-platform-directory/nuxeo-platform-directory-sql/src/main/java/org/nuxeo/ecm/directory/sql/.

Source file: SQLHelper.java

  21 
vote

private Set<String> getPhysicalColumns() throws SQLException {
  ResultSet rs=null;
  Set<String> columnNames=new HashSet<String>();
  try {
    DatabaseMetaData metadata=connection.getMetaData();
    rs=metadata.getColumns(null,"%",tableName,"%");
    while (rs.next()) {
      columnNames.add(rs.getString("COLUMN_NAME"));
    }
  }
  finally {
    try {
      if (rs != null) {
        rs.close();
      }
    }
 catch (    Exception e) {
      log.warn("Error while trying to close result set",e);
    }
  }
  return columnNames;
}
 

Example 39

From project osw-openfire-plugin, under directory /src/java/org/onesocialweb/openfire/.

Source file: OswPlugin.java

  21 
vote

/** 
 * Tries to identify the type of DB used in the Openfire server and to obtain the connection parameters. This parameters can later be passed when creating the entity manager factory to avoid reading this from the persistance.xml file.
 */
private void setConnectionProperties(){
  String driver="";
  String serverURL="";
  String username="";
  String password="";
  String connectionProvider=JiveGlobals.getXMLProperty("connectionProvider.className");
  if (connectionProvider.trim().equalsIgnoreCase(DefaultConnectionProvider.class.getName())) {
    driver=JiveGlobals.getXMLProperty("database.defaultProvider.driver");
    serverURL=JiveGlobals.getXMLProperty("database.defaultProvider.serverURL");
    username=JiveGlobals.getXMLProperty("database.defaultProvider.username");
    password=JiveGlobals.getXMLProperty("database.defaultProvider.password");
  }
 else {
    try {
      DatabaseMetaData metadata=DbConnectionManager.getConnection().getMetaData();
      driver="org.hsqldb.jdbcDriver";
      serverURL=metadata.getURL();
      username=metadata.getUserName();
      password="";
    }
 catch (    SQLException e) {
      Log.error("Cannot recognise the Database.." + e.getMessage());
    }
  }
  connProperties.put("openjpa.ConnectionURL",serverURL);
  connProperties.put("openjpa.ConnectionDriverName",driver);
  connProperties.put("openjpa.ConnectionUserName",username);
  connProperties.put("openjpa.ConnectionPassword",password);
  connProperties.put("openjpa.Log","DefaultLevel=INFO, Tool=INFO");
  connProperties.put("openjpa.jdbc.SynchronizeMappings","buildSchema(ForeignKeys=true)");
  connProperties.put("openjpa.Multithreaded","true");
}
 

Example 40

From project querydsl, under directory /querydsl-sql/src/test/java/com/mysema/query/.

Source file: TypesBase.java

  21 
vote

@Test @ExcludeIn({CUBRID,POSTGRES}) public void DumpTypes() throws SQLException {
  Connection conn=Connections.getConnection();
  DatabaseMetaData md=conn.getMetaData();
  ResultSet rs=md.getUDTs(null,null,null,null);
  try {
    while (rs.next()) {
      String cat=rs.getString(1);
      String schema=rs.getString(2);
      String name=rs.getString(3);
      String classname=rs.getString(4);
      String datatype=rs.getString(5);
      String remarks=rs.getString(6);
      String base_type=rs.getString(7);
      System.out.println(name + " " + classname+ " "+ datatype+ " "+ remarks+ " "+ base_type);
      ResultSet rs2=md.getAttributes(cat,schema,name,null);
      try {
        while (rs2.next()) {
          String _cat=rs2.getString(1);
          String _schema=rs2.getString(2);
          String _name=rs2.getString(3);
          String _attr_name=rs2.getString(4);
          String _data_type=rs2.getString(5);
          String _attr_type_name=rs2.getString(6);
          String _attr_size=rs2.getString(7);
          System.out.println(" " + _attr_name + " "+ _data_type+ " "+ _attr_type_name+ " "+ _attr_size);
        }
      }
  finally {
        rs2.close();
      }
    }
  }
  finally {
    rs.close();
  }
}
 

Example 41

From project scooter, under directory /source/src/com/scooterframework/orm/sqldataexpress/util/.

Source file: SqlExpressUtil.java

  21 
vote

/** 
 * Returns a list of TableInfo instances for a database connection name.
 * @param connName the database connection name
 * @param catalog a catalog name; must match the catalog name as it is stored in the database; "" retrieves those without a catalog; <tt>null</tt> means that the catalog name should not be used to narrow the search
 * @param schema a schema name; must match the schema name as it is stored in the database; "" retrieves those without a schema; <tt>null</tt> means that the schema name should not be used to narrow the search
 * @param tableName a table name; must match the table name as it is stored in the database
 * @param types a list of table types to include; <tt>null</tt> returns all types
 * @return a list of TableInfo instances
 * @throws java.sql.SQLException
 */
public static List<TableInfo> getDatabaseTables(String connName,String catalog,String schema,String tableName,String[] types) throws SQLException {
  DBAdapter dba=DBAdapterFactory.getInstance().getAdapter(connName);
  catalog=toUpperCaseIfAllowed(dba,catalog);
  schema=toUpperCaseIfAllowed(dba,schema);
  tableName=toUpperCaseIfAllowed(dba,tableName);
  List<TableInfo> list=new ArrayList<TableInfo>();
  Connection conn=null;
  ResultSet rs=null;
  try {
    conn=getConnection(connName);
    DatabaseMetaData dbmd=conn.getMetaData();
    rs=dbmd.getTables(catalog,schema,tableName,types);
    while (rs.next()) {
      TableInfo ti=new TableInfo();
      ti.setCatalog(rs.getString("TABLE_CAT"));
      ti.setName(rs.getString("TABLE_NAME"));
      ti.setRemarks(rs.getString("REMARKS"));
      ti.setSchema(rs.getString("TABLE_SCHEM"));
      ti.setType(rs.getString("TABLE_TYPE"));
      list.add(ti);
    }
    rs.close();
  }
 catch (  SQLException ex) {
    throw ex;
  }
 finally {
    DAOUtil.closeResultSet(rs);
    DAOUtil.closeConnection(conn);
  }
  return list;
}
 

Example 42

From project sparsemapcontent, under directory /core/src/main/java/org/sakaiproject/nakamura/lite/storage/jdbc/.

Source file: JDBCStorageClientPool.java

  21 
vote

protected JDBCStorageClient checkSchema(Object o){
  JDBCStorageClient client=(JDBCStorageClient)o;
synchronized (sqlConfigLock) {
    if (!schemaHasBeenChecked) {
      try {
        Connection connection=client.getConnection();
        DatabaseMetaData metadata=connection.getMetaData();
        LOGGER.info("Starting Sparse Map Content database ");
        LOGGER.info("   Database Vendor: {} {}",metadata.getDatabaseProductName(),metadata.getDatabaseProductVersion());
        LOGGER.info("   Database Driver: {} ",properties.get(JDBC_DRIVER));
        LOGGER.info("   Database URL   : {} ",properties.get(CONNECTION_URL));
        client.checkSchema(getClientConfigLocations(client.getConnection()));
        schemaHasBeenChecked=true;
        indexColumnsMap=client.syncIndexColumns();
      }
 catch (      Throwable e) {
        LOGGER.warn("Failed to check Schema",e);
      }
    }
  }
  return client;
}
 

Example 43

From project springside4, under directory /modules/core/src/test/java/org/springside/modules/persistence/.

Source file: HibernatesTest.java

  21 
vote

@Test public void testGetDialect() throws SQLException {
  DataSource mockDataSource=Mockito.mock(DataSource.class);
  Connection mockConnection=Mockito.mock(Connection.class);
  DatabaseMetaData mockMetaData=Mockito.mock(DatabaseMetaData.class);
  Mockito.when(mockDataSource.getConnection()).thenReturn(mockConnection);
  Mockito.when(mockConnection.getMetaData()).thenReturn(mockMetaData);
  Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:h2:file:~/test;AUTO_SERVER=TRUE");
  String dialect=Hibernates.getDialect(mockDataSource);
  assertEquals(H2Dialect.class.getName(),dialect);
  Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:mysql://localhost:3306/test");
  dialect=Hibernates.getDialect(mockDataSource);
  assertEquals(MySQL5InnoDBDialect.class.getName(),dialect);
  Mockito.when(mockMetaData.getURL()).thenReturn("jdbc:oracle:thin:@127.0.0.1:1521:XE");
  dialect=Hibernates.getDialect(mockDataSource);
  assertEquals(Oracle10gDialect.class.getName(),dialect);
}
 

Example 44

From project aws-toolkit-for-eclipse, under directory /com.amazonaws.eclipse.datatools.enablement.simpledb/src/com/amazonaws/eclipse/datatools/enablement/simpledb/driver/.

Source file: JdbcConnection.java

  19 
vote

public DatabaseMetaData getMetaData() throws SQLException {
  if (this.metaData == null) {
    this.metaData=new JdbcDatabaseMetaData(this);
  }
  return this.metaData;
}
 

Example 45

From project hibernate-tools, under directory /src/java/org/hibernate/cfg/reveng/dialect/.

Source file: AbstractMetaDataDialect.java

  19 
vote

protected DatabaseMetaData getMetaData() throws JDBCBinderException {
  if (metaData == null) {
    try {
      metaData=getConnection().getMetaData();
    }
 catch (    SQLException e) {
      throw getSQLExceptionConverter().convert(e,"Getting database metadata",null);
    }
  }
  return metaData;
}
 

Example 46

From project karaf, under directory /main/src/test/java/org/apache/karaf/main/lock/.

Source file: BaseJDBCLockTest.java

  19 
vote

@Before public void setUp() throws Exception {
  connection=EasyMock.createMock(Connection.class);
  metaData=EasyMock.createMock(DatabaseMetaData.class);
  resultSet=EasyMock.createMock(ResultSet.class);
  preparedStatement=EasyMock.createMock(PreparedStatement.class);
  statement=EasyMock.createMock(Statement.class);
  props=new Properties();
  props.put("karaf.lock.jdbc.url",url);
  props.put("karaf.lock.jdbc.driver",driver);
  props.put("karaf.lock.jdbc.user",user);
  props.put("karaf.lock.jdbc.password",password);
  props.put("karaf.lock.jdbc.table",tableName);
  props.put("karaf.lock.jdbc.clustername",clustername);
  props.put("karaf.lock.jdbc.timeout",timeout);
}
 

Example 47

From project miso-lims, under directory /sqlstore/src/main/java/uk/ac/bbsrc/tgac/miso/sqlstore/util/.

Source file: DbUtils.java

  19 
vote

public Object processMetaData(DatabaseMetaData dbmd) throws SQLException {
  ResultSet rs=dbmd.getTables(catalog,null,null,new String[]{"TABLE"});
  ArrayList l=new ArrayList();
  while (rs.next()) {
    l.add(rs.getString(3));
  }
  return l;
}
 

Example 48

From project objectos-comuns-dbunit, under directory /src/main/java/br/com/objectos/comuns/testing/dbunit/.

Source file: MySqlMetadataHandler.java

  19 
vote

@Override public ResultSet getTables(DatabaseMetaData metaData,String schemaName,String[] tableType) throws SQLException {
  if (catalogs.isEmpty()) {
    return super.getTables(metaData,schemaName,tableType);
  }
 else {
    Iterable<List<MysqlTable>> listses=Iterables.transform(catalogs,new ToTableResultSet(metaData,tableType));
    Iterable<MysqlTable> tables=Iterables.concat(listses);
    return new ResultSetImpl(tables);
  }
}