@Test public void testMetaFunctionsLocal() throws Exception { final Connection connection = CalciteAssert.hr().connect(); assertThat(connection.isClosed(), is(false)); for (Meta.DatabaseProperty p : Meta.DatabaseProperty.values()) { switch (p) { case GET_NUMERIC_FUNCTIONS: assertThat(connection.getMetaData().getNumericFunctions(), not(equalTo(""))); break; case GET_SYSTEM_FUNCTIONS: assertThat(connection.getMetaData().getSystemFunctions(), CoreMatchers.notNullValue()); break; case GET_TIME_DATE_FUNCTIONS: assertThat(connection.getMetaData().getTimeDateFunctions(), not(equalTo(""))); break; case GET_S_Q_L_KEYWORDS: assertThat(connection.getMetaData().getSQLKeywords(), not(equalTo(""))); break; case GET_STRING_FUNCTIONS: assertThat(connection.getMetaData().getStringFunctions(), not(equalTo(""))); break; default: } } connection.close(); assertThat(connection.isClosed(), is(true)); }
public ResultSet getProcedures(String schemaPattern, String procedureNamePattern) { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } try { return connection .getMetaData() .getProcedures(connection.getCatalog(), schemaPattern, procedureNamePattern); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } } try { return connection .getMetaData() .getProcedures(connection.getCatalog(), schemaPattern, procedureNamePattern); } catch (SQLException e) { try { reconnect(); return connection .getMetaData() .getProcedures(connection.getCatalog(), schemaPattern, procedureNamePattern); } catch (Exception e1) { logger.log(Level.WARNING, e.getMessage(), e); return null; } } }
protected synchronized String getProcedureName(Connection dConn, Connection gConn) { /// avoid #42569 ResultSet rs = null; try { rs = gConn.getMetaData().getProcedures(null, null, null); List procNames = ResultSetHelper.asList(rs, false); Log.getLogWriter().info("procedure names are " + ResultSetHelper.listToString(procNames)); rs.close(); } catch (SQLException se) { SQLHelper.handleSQLException(se); } try { rs = gConn.getMetaData().getFunctions(null, null, null); } catch (SQLException se) { SQLHelper.handleSQLException(se); } List funcNames = ResultSetHelper.asList(rs, false); Log.getLogWriter().info("function names are " + ResultSetHelper.listToString(funcNames)); if (procedureNames == null) { ArrayList<String> procs = new ArrayList<String>(); procs.addAll(ProcedureDDLStmt.modifyProcNameList); procs.addAll(ProcedureDDLStmt.nonModifyProcNameList); procedureNames = new ArrayList<String>(procs); } return procedureNames.get(SQLTest.random.nextInt(procedureNames.size())); }
public ResultSet getAllSchemas() { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } try { return connection.getMetaData().getSchemas(); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } } try { return connection.getMetaData().getSchemas(); } catch (SQLException e) { try { reconnect(); return connection.getMetaData().getSchemas(); } catch (Exception e1) { logger.log(Level.WARNING, e.getMessage(), e); return null; } } }
public String getIdentifierQuoteString() { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return ""; } try { return connection.getMetaData().getIdentifierQuoteString(); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return ""; } } try { return connection.getMetaData().getIdentifierQuoteString(); } catch (SQLException e) { try { reconnect(); return connection.getMetaData().getIdentifierQuoteString(); } catch (Exception e1) { logger.log(Level.WARNING, e.getMessage(), e); return ""; } } }
public boolean isSupportProcedure() { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return false; } try { return connection.getMetaData().supportsStoredProcedures(); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return false; } } try { return connection.getMetaData().supportsStoredProcedures(); } catch (SQLException e) { try { reconnect(); return connection.getMetaData().supportsStoredProcedures(); } catch (Exception e1) { logger.log(Level.WARNING, e.getMessage(), e); return true; } } }
public ResultSet getAlltables(String schemaPattern, String namePattern, String[] types) { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } try { return connection.getMetaData().getTables(getCatalog(), schemaPattern, namePattern, types); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } catch (Exception ex) { return null; } } try { return connection.getMetaData().getTables(getCatalog(), schemaPattern, namePattern, types); } catch (SQLException e) { try { reconnect(); return connection.getMetaData().getTables(getCatalog(), schemaPattern, namePattern, types); } catch (SQLException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); return null; } catch (OdaException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); return null; } } }
public ResultSet getTableTypes() { if (connection == null) { try { reconnect(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } try { return connection.getMetaData().getTableTypes(); } catch (SQLException e) { logger.log(Level.WARNING, e.getMessage(), e); return null; } catch (Exception ex) { return null; } } try { return connection.getMetaData().getTableTypes(); } catch (SQLException e) { try { reconnect(); return connection.getMetaData().getTableTypes(); } catch (SQLException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); return null; } catch (OdaException ex) { logger.log(Level.WARNING, ex.getMessage(), ex); return null; } } }
/* (非 Javadoc) * @see com.lavans.util.jdbc.ConnectionPool#createConnection() */ @Override protected PooledConnection createConnection() throws SQLException { // 最大数チェック if ((getPoolList().size() + getUseList().size()) >= getMaxConnections()) { throw new SQLException( MSG_ERR_TOOMANYCONNECTIONS, SQLSTATE_CONNECTION_EXCEPTION, ERR_CONNECTION_OVERFLOW); } Connection conn = createNativeConnection(); conn = new ClusterConnection(conn, this); logger.debug(conn.getMetaData().getURL()); urlMap.put(conn, conn.getMetaData().getURL()); // コネクションと新しいurlのマッピングを行う。 // StatsConnection,LoggingConnectionともにLoggableインターフェースの // 実装とした。LoggableなConnectionの作成順序は入れ替え可能。 // Loggableを実装しないラッパークラスを作る場合はこれらの前にnewすること。 // 統計情報を収集するなら if (isStatistics()) { conn = new StatsConnection(conn); } // BindConnection型を返すので、BindConnectionでラップするのは // 一番最後でないといけない。 BindConnection bcon = new BindConnectionImpl(conn); // さらにConnection#close()で物理的に閉じずにDBManagerに // 返却するためPooledConnectionでラップする。 // ConnectionPoolではなくDBManagerを通すのは // 統計情報取得時に貸し出し管理を行うため。 PooledConnection pcon = new PooledConnection(this, bcon); return pcon; }
private static boolean isSetLongSupported(java.sql.Connection _conn) throws SQLException { if (_conn.getMetaData().getDatabaseProductName().equalsIgnoreCase("ACCESS") && _conn.getMetaData().getDriverName().startsWith("JDBC-ODBC Bridge")) { return false; } else { return true; } }
public static synchronized Stack<Evolution> listDatabaseEvolutions(String moduleKey) { Stack<Evolution> evolutions = new Stack<Evolution>(); evolutions.add(new Evolution("", 0, "", "", false)); Connection connection = null; try { connection = EvolutionQuery.getNewConnection(); String tableName = "play_evolutions"; boolean tableExists = true; ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null); if (!rs.next()) { // Table in lowercase does not exist // oracle gives table names in upper case tableName = tableName.toUpperCase(); Logger.trace("Checking " + tableName); rs.close(); rs = connection.getMetaData().getTables(null, null, tableName, null); // Does it exist? if (!rs.next()) { // did not find it in uppercase either tableExists = false; } } // Do we have a if (tableExists) { checkAndUpdateEvolutionsForMultiModuleSupport(connection); ResultSet databaseEvolutions = EvolutionQuery.getEvolutions(connection, moduleKey); while (databaseEvolutions.next()) { Evolution evolution = new Evolution( moduleKey, databaseEvolutions.getInt(1), databaseEvolutions.getString(3), databaseEvolutions.getString(4), false); evolutions.add(evolution); } } else { EvolutionQuery.createTable(); } } catch (SQLException e) { Logger.error(e, "SQL error while checking play evolutions"); } finally { EvolutionQuery.closeConnection(connection); } Collections.sort(evolutions); return evolutions; }
/** * 別の接続先を取得する。 このメソッドが呼ばれるのはClusterConnectionが接続している先のDBに 障害があったとき。したがって、エラーが発生していないurlの中から * 有効なurlを探索し、Connectionを生成して返してやる。 BindやLogginはClusterConnectionの上にラップされているので、 ここでは意識する必要はない。 * * @return */ public Connection getAnotherConnection(ClusterConnection target) throws SQLException { String url = urlMap.remove(target); List<String> workList = new ArrayList<String>(urlList); // urlListをコピーして workList.remove(url); // 障害が起きたurlを除外する。 Connection conn = createNativeConnection(workList); logger.debug(conn.getMetaData().getURL()); urlMap.put(target, conn.getMetaData().getURL()); // コネクションと新しいurlのマッピングを行う。 return conn; }
/** * gets the connection key. return null if it cannot be determined. * * @return the key or null */ private static String getConnectionKey(Connection con) { String uName = null; String url = null; try { uName = con.getMetaData().getUserName(); url = con.getMetaData().getURL(); } catch (SQLException e) { LOG.error("unable to get DB url", e); } return uName != null && url != null ? uName + " @ " + url : null; }
/** Gets a title for the data presented in the tree node. */ public String getTitle() { try { Connection con = conProv.getConnection(); DatabaseMetaData dmd = con.getMetaData(); StringBuffer sb = new StringBuffer(); sb.append(dmd.getDatabaseProductName()); sb.append(" - "); dmd = con.getMetaData(); sb.append(conProv.getServerName()); return sb.toString(); } catch (Exception e) { return "[Not Connected]"; } }
@Test public void testTableMetadataScan() throws Exception { Connection conn = DriverManager.getConnection(getUrl()); try { // make sure connections w/o tenant id only see non-tenant-specific tables, both SYSTEM and // USER DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getTables(null, null, null, null); assertTrue(rs.next()); assertTableMetaData(rs, TYPE_SCHEMA, TYPE_SEQUENCE, SYSTEM); assertTrue(rs.next()); assertTableMetaData(rs, TYPE_SCHEMA, TYPE_TABLE, SYSTEM); assertTrue(rs.next()); assertTableMetaData(rs, null, PARENT_TABLE_NAME, USER); assertFalse(rs.next()); // make sure connections w/o tenant id only see non-tenant-specific columns rs = meta.getColumns(null, null, null, null); while (rs.next()) { assertNotEquals(TENANT_TABLE_NAME, rs.getString("TABLE_NAME")); } } finally { conn.close(); } conn = DriverManager.getConnection(PHOENIX_JDBC_TENANT_SPECIFIC_URL); try { // make sure tenant-specific connections only see their own tables DatabaseMetaData meta = conn.getMetaData(); ResultSet rs = meta.getTables(null, null, null, null); assertTrue(rs.next()); assertTableMetaData(rs, null, TENANT_TABLE_NAME, USER); assertFalse(rs.next()); // make sure tenants see paren table's columns and their own rs = meta.getColumns(null, null, null, null); assertTrue(rs.next()); assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "user"); assertTrue(rs.next()); assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "tenant_id"); assertTrue(rs.next()); assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "id"); assertTrue(rs.next()); assertColumnMetaData(rs, null, TENANT_TABLE_NAME, "tenant_col"); assertFalse(rs.next()); } finally { conn.close(); } }
public PostgresClientManager() { try { connection = DriverManager.getConnection(url, "postgres", "kuba22"); statement = connection.createStatement(); ResultSet rs = connection.getMetaData().getTables(null, null, null, null); boolean tableExists = false; while (rs.next()) { if (rs.getString("TABLE_NAME").equalsIgnoreCase("Client")) { tableExists = true; break; } } if (!tableExists) { statement.executeUpdate(createTable); } getAllClient = connection.prepareStatement("" + "Select * From Klient"); deleteClient = connection.prepareStatement("" + "DELETE From Klient where name=?"); getClient = connection.prepareStatement("" + "SELECT * From Klient where id=?"); } catch (SQLException e) { e.printStackTrace(); } }
private final void detectDialect() { Connection conn = null; try { conn = dataSource.getConnection(); final DatabaseMetaData dbmd = conn.getMetaData(); final String dbProductName = dbmd.getDatabaseProductName(); if ("Microsoft SQL Server".equalsIgnoreCase(dbProductName)) { dialect = new MssqlDialect(); } else if ("MySQL".equalsIgnoreCase(dbProductName)) { dialect = new MysqlDialect(); } else if ("Oracle".equalsIgnoreCase(dbProductName)) { dialect = new OracleDialect(); } else { // 默认是Oracle dialect = new OracleDialect(); } } catch (Exception ex) { dialect = new OracleDialect(); } finally { if (conn != null) { try { conn.close(); } catch (Exception ex) { } conn = null; } } }
private void fetchPrimaryKeys() { Vector temp = new Vector(20); try { if (cConn == null) { return; } if (dbmeta == null) { dbmeta = cConn.getMetaData(); } ResultSet colList = dbmeta.getPrimaryKeys(null, null, tableName); while (colList.next()) { temp.addElement(colList.getString("COLUMN_NAME")); } colList.close(); } catch (SQLException e) { ZaurusEditor.printStatus("SQL Exception: " + e.getMessage()); } primaryKeys = new String[temp.size()]; temp.copyInto(primaryKeys); pkColIndex = new int[primaryKeys.length]; for (int i = 0; i < primaryKeys.length; i++) { pkColIndex[i] = this.getColIndex(primaryKeys[i]); } // end of for (int i=0; i<primaryKeys.length; i++) }
// answer the index of the column named colName in the table tabName private int getColIndex(String colName, String tabName) { int ordPos = 0; try { if (cConn == null) { return -1; } if (dbmeta == null) { dbmeta = cConn.getMetaData(); } ResultSet colList = dbmeta.getColumns(null, null, tabName, colName); colList.next(); ordPos = colList.getInt("ORDINAL_POSITION"); colList.close(); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } return ordPos - 1; }
private ImmutableMap<String, JdbcTable> computeTables() { Connection connection = null; ResultSet resultSet = null; try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); resultSet = metaData.getTables(catalog, schema, null, null); final ImmutableMap.Builder<String, JdbcTable> builder = ImmutableMap.builder(); while (resultSet.next()) { final String tableName = resultSet.getString(3); final String catalogName = resultSet.getString(1); final String schemaName = resultSet.getString(2); final String tableTypeName = resultSet.getString(4); // Clean up table type. In particular, this ensures that 'SYSTEM TABLE', // returned by Phoenix among others, maps to TableType.SYSTEM_TABLE. // We know enum constants are upper-case without spaces, so we can't // make things worse. final String tableTypeName2 = tableTypeName.toUpperCase().replace(' ', '_'); final TableType tableType = Util.enumVal(TableType.class, tableTypeName2); final JdbcTable table = new JdbcTable(this, catalogName, schemaName, tableName, tableType); builder.put(tableName, table); } return builder.build(); } catch (SQLException e) { throw new RuntimeException("Exception while reading tables", e); } finally { close(connection, null, resultSet); } }
private void testAll(ArrayList<Database> dbs, ArrayList<Bench> tests, int size) throws Exception { for (int i = 0; i < dbs.size(); i++) { if (i > 0) { Thread.sleep(1000); } // calls garbage collection TestBase.getMemoryUsed(); Database db = dbs.get(i); System.out.println("Testing the performance of " + db.getName()); db.startServer(); Connection conn = db.openNewConnection(); DatabaseMetaData meta = conn.getMetaData(); System.out.println( " " + meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion()); runDatabase(db, tests, 1); runDatabase(db, tests, 1); collect = true; runDatabase(db, tests, size); conn.close(); db.log("Executed statements", "#", db.getExecutedStatements()); db.log("Total time", "ms", db.getTotalTime()); int statPerSec = db.getExecutedStatements() * 1000 / db.getTotalTime(); db.log("Statements per second", "#", statPerSec); System.out.println("Statements per second: " + statPerSec); collect = false; db.stopServer(); } }
@Test public void testHsqldbLocalServer() throws ClassNotFoundException, SQLException { LOG.info("HSQLDB: Running User: {}", System.getProperty("user.name")); LOG.info( "HSQLDB: Loading the JDBC Driver: {}", propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_DRIVER_KEY)); Class.forName(propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_DRIVER_KEY)); // Get the connection Connection connection = DriverManager.getConnection( propertyParser.getProperty(ConfigVars.HSQLDB_JDBC_CONNECTION_STRING_PREFIX_KEY) + propertyParser.getProperty(ConfigVars.HSQLDB_HOSTNAME_KEY) + ":" + propertyParser.getProperty(ConfigVars.HSQLDB_PORT_KEY) + "/" + propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY), "SA", ""); assertThat( connection.getMetaData().getURL(), containsString(propertyParser.getProperty(ConfigVars.HSQLDB_DATABASE_NAME_KEY))); }
@BeforeClass public static void setUp() throws Exception { server = new FakeServer(true); server.deployVDB(VDB, UnitTestUtil.getTestDataPath() + "/PartsSupplier.vdb"); connection = server.createConnection("jdbc:teiid:" + VDB); // $NON-NLS-1$ //$NON-NLS-2$ dbMetadata = connection.getMetaData(); }
/** Check for any open connections */ public void finalize() { StringBuilder sbDBNames = new StringBuilder(m_htConnections.size() * 20); if (m_htConnections.size() > 0) { int iOpenConnections = m_htConnections.size(); // force them all to be cleared.... Enumeration en = m_htConnections.keys(); while (en.hasMoreElements()) { Connection cx = (Connection) en.nextElement(); try { String sDBName = cx.getMetaData().getDatabaseProductName(); if (sDBName.length() > 0) { if (sbDBNames.length() > 0) sbDBNames.append(','); sbDBNames.append(sDBName); } } catch (Exception e) { } releaseDataConnection(cx); m_htConnections.remove(cx); } m_SysCtx.doError( "pmaSystem.ReleaseConnection", new String[] {"" + iOpenConnections, sbDBNames.toString()}, this); } }
public static void main(String[] args) throws SQLException { java.sql.Connection conn = JdbcUtils.getConnection(); DatabaseMetaData dbmd = conn.getMetaData(); System.out.println("db name: " + dbmd.getDatabaseProductName()); System.out.println("tx: " + dbmd.supportsTransactions()); conn.close(); }
SqlDialect get(DataSource dataSource) { Connection connection = null; try { connection = dataSource.getConnection(); DatabaseMetaData metaData = connection.getMetaData(); String productName = metaData.getDatabaseProductName(); String productVersion = metaData.getDatabaseProductVersion(); List key = Arrays.asList(productName, productVersion); SqlDialect dialect = map.get(key); if (dialect == null) { final SqlDialect.DatabaseProduct product = SqlDialect.getProduct(productName, productVersion); dialect = new SqlDialect(product, productName, metaData.getIdentifierQuoteString()); map.put(key, dialect); } connection.close(); connection = null; return dialect; } catch (SQLException e) { throw new RuntimeException(e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { // ignore } } } }
public List<ColsInfo> getIn(String tableName) { List<ColsInfo> listOfLists = new ArrayList<ColsInfo>(); try { ResultSet rsColumns = null; DatabaseMetaData meta = connect.getMetaData(); rsColumns = meta.getColumns(null, "%", tableName, "%"); Statement st; st = connect.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM " + tableName); ResultSetMetaData rsMetaData = rs.getMetaData(); int i = 1; while (rsColumns.next()) { ColsInfo tmp = new ColsInfo(); tmp.setColTitle(rsColumns.getString("COLUMN_NAME")); tmp.setColType(rsColumns.getString("TYPE_NAME")); tmp.setColSize(rsColumns.getInt("COLUMN_SIZE")); tmp.setColPosition(rsColumns.getInt("ORDINAL_POSITION")); tmp.setIsNullable(rsColumns.getInt("NULLABLE")); tmp.setAutoIncrement(rsMetaData.isAutoIncrement(i)); i++; listOfLists.add(tmp); } return listOfLists; } catch (SQLException e) { e.printStackTrace(); return null; } }
public boolean tableExists(Connection connection, TableName tableName) throws PersistenceException { if (tableName == null) { throw new NullPointerException("table name is mandatory"); } ResultSet rs = null; try { // we need to make sure, that (even if the user has extended permissions) only the tables in // current schema are checked // explicit set of the schema to the current user one to make sure only tables of the current // users are requested DatabaseMetaData metaData = connection.getMetaData(); String schemaPattern = tableName.getSchema(); if (schemaPattern == null) { switch (getDialect()) { case ORACLE: schemaPattern = metaData.getUserName(); break; default: } } rs = metaData.getTables(null, schemaPattern, tableName.getName(), new String[] {"TABLE"}); return rs.next(); } catch (SQLException e) { if (trace) log.tracef(e, "SQLException occurs while checking the table %s", tableName); return false; } finally { JdbcUtil.safeClose(rs); } }
public void dropSQLJSchema() throws SQLException { Statement stmt = m_connection.createStatement(); Savepoint p = null; try { if (m_connection.getMetaData().supportsSavepoints()) { p = m_connection.setSavepoint(); } stmt.execute("DROP LANGUAGE java CASCADE"); stmt.execute("DROP LANGUAGE javaU CASCADE"); } catch (SQLException e) { /* roll back to savepoint (if available) * or restart the transaction (if no savepoint is available) * & ignore the exception */ if (p != null) { m_connection.rollback(p); } else { /* Assuming that the dropSQLJSchema is the * first method called in a transaction, * we can afford to restart the transaction. * * This solution is designed for PostgreSQL < 8 (no savepoints available) */ m_connection.rollback(); } } finally { if (p != null) { m_connection.releaseSavepoint(p); } } stmt.execute("DROP SCHEMA sqlj CASCADE"); stmt.close(); }
/** * 创建一个新的数据库连接并返回它 * * @return 返回一个新创建的数据库连接 */ private Connection newConnection() throws SQLException { // 创建一个数据库连接 Connection conn = DriverManager.getConnection( this.param.getUrl(), this.param.getUser(), this.param.getPassword()); // 如果这是第一次创建数据库连接,即检查数据库,获得此数据库允许支持的 // 最大客户连接数目 // connections.size()==0 表示目前没有连接己被创建 if (connections.size() == 0) { DatabaseMetaData metaData = conn.getMetaData(); int driverMaxConnections = metaData.getMaxConnections(); // 数据库返回的 driverMaxConnections 若为 0 ,表示此数据库没有最大 // 连接限制,或数据库的最大连接限制不知道 // driverMaxConnections 为返回的一个整数,表示此数据库允许客户连接的数 目 // 如果连接池中设置的最大连接数量大于数据库允许的连接数目 , 则置连接池 的最大 // 连接数目为数据库允许的最大数目 if (driverMaxConnections > 0 && this.param.getMaxConnection() > driverMaxConnections) { this.param.setMaxConnection(driverMaxConnections); } } return conn; // 返回创建的新的数据库连接 }