コード例 #1
0
 @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));
 }
コード例 #2
0
 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;
     }
   }
 }
コード例 #3
0
  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()));
  }
コード例 #4
0
 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;
     }
   }
 }
コード例 #5
0
 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 "";
     }
   }
 }
コード例 #6
0
 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;
     }
   }
 }
コード例 #7
0
 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;
     }
   }
 }
コード例 #8
0
 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;
     }
   }
 }
コード例 #9
0
  /* (非 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;
  }
コード例 #10
0
 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;
   }
 }
コード例 #11
0
ファイル: Evolutions.java プロジェクト: hsch/play1
  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;
  }
コード例 #12
0
  /**
   * 別の接続先を取得する。 このメソッドが呼ばれるのは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;
  }
コード例 #13
0
    /**
     * 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;
    }
コード例 #14
0
 /** 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]";
   }
 }
コード例 #15
0
  @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();
    }
  }
コード例 #16
0
  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();
    }
  }
コード例 #17
0
ファイル: DialectFactory.java プロジェクト: LD00000/escmDemo
  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;
      }
    }
  }
コード例 #18
0
  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++)
  }
コード例 #19
0
  // 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;
  }
コード例 #20
0
ファイル: JdbcSchema.java プロジェクト: NGDATA/optiq
 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);
   }
 }
コード例 #21
0
 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)));
  }
コード例 #23
0
 @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();
 }
コード例 #24
0
 /** 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);
   }
 }
コード例 #25
0
ファイル: DBMetaData.java プロジェクト: airings/codeLibrary
 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();
 }
コード例 #26
0
ファイル: JdbcUtils.java プロジェクト: new-emacs/optiq
 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
       }
     }
   }
 }
コード例 #27
0
 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;
   }
 }
コード例 #28
0
 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);
   }
 }
コード例 #29
0
ファイル: Deployer.java プロジェクト: ChiralBehaviors/pljava
  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();
  }
コード例 #30
0
  /**
   * 创建一个新的数据库连接并返回它
   *
   * @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; // 返回创建的新的数据库连接
  }