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()));
  }
Example #2
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;
    }
  public void checkTables(consumer<Boolean> consumer) {

    Connection connection = null;
    ResultSet result = null;

    try {

      connection = HikariManager.getInstance().getConnection();

      DatabaseMetaData dbm = connection.getMetaData();

      boolean playersExists = false;
      boolean periodicExists = false;
      boolean allExist = false;

      result = dbm.getTables(null, null, HikariManager.getInstance().prefix + "players", null);
      if (result.next()) playersExists = true;

      result = dbm.getTables(null, null, HikariManager.getInstance().prefix + "periodic", null);
      if (result.next()) periodicExists = true;

      if (playersExists && periodicExists) allExist = true;

      if (consumer != null) consumer.accept(allExist);

    } catch (SQLException e) {

      e.printStackTrace();

    } finally {

      HikariManager.getInstance().close(connection, null, result);
    }
  }
Example #4
0
 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
       }
     }
   }
 }
Example #5
0
 /**
  * Constructor creates and initializes the meta data object create DS object per table
  *
  * @param tableNames - String array of database table names ,It can be zero element array
  * @param singleService - select the service generation mode true one service for whole database
  *     when it false services per table wise
  * @param dataSourceId - carbon datasource id it can be null
  *     <p>When create the connection there are 3 away to do it , First way is provide the relevant
  *     information(url, driver, username, password) which need to create connection that time
  *     other fields(connection, datasourceId) should be null
  *     <p>Second way directly you can provide connection instance
  *     <p>final way is you can provide carbon datasource id(name)
  *     <p>if you wish to use all the tables of database you can provide zero element array
  */
 public DSGenerator(
     String dataSourceId,
     String dbName,
     String[] schemas,
     String[] tableNames,
     boolean singleService,
     String nameSpace,
     String serviceName) {
   this.DSErrorList = new ArrayList<String>();
   try {
     Connection connection;
     String[] tableNameList = tableNames;
     if (dataSourceId != null) {
       connection = createConnection(dataSourceId);
       DatabaseMetaData metaObject = connection.getMetaData();
       if (tableNameList.length == 0) {
         tableNameList = DSGenerator.getTableList(connection, dbName, schemas);
       }
       if (singleService) {
         this.generatedService =
             generateService(
                 dataSourceId, dbName, schemas, tableNameList, metaObject, nameSpace, serviceName);
       } else {
         this.generatedServiceList =
             generateServices(dataSourceId, dbName, schemas, tableNameList, metaObject, nameSpace);
       }
       connection.close();
     }
   } catch (Exception e) {
     log.error("Meta Object initialization failed due to ", e);
   }
 }
Example #6
0
 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 Table createTable(Connection conn, ResultSet rs) throws SQLException {
    String realTableName = null;
    try {
      ResultSetMetaData rsMetaData = rs.getMetaData();
      String schemaName = rs.getString("TABLE_SCHEM") == null ? "" : rs.getString("TABLE_SCHEM");
      realTableName = rs.getString("TABLE_NAME");
      String tableType = rs.getString("TABLE_TYPE");
      String remarks = rs.getString("REMARKS");
      if (remarks == null && dbHelper.isOracleDataBase()) {
        remarks = getOracleTableComments(realTableName);
      }

      Table table = new Table();
      table.setSqlName(realTableName);
      table.setRemarks(remarks);

      if ("SYNONYM".equals(tableType) && dbHelper.isOracleDataBase()) {
        table.setOwnerSynonymName(getSynonymOwner(realTableName));
      }

      retriveTableColumns(table);

      table.initExportedKeys(conn.getMetaData());
      table.initImportedKeys(conn.getMetaData());
      BeanHelper.copyProperties(
          table, TableOverrideValuesProvider.getTableOverrideValues(table.getSqlName()));
      return table;
    } catch (SQLException e) {
      throw new RuntimeException("create table object error,tableName:" + realTableName, e);
    }
  }
  public static boolean checkDBExists(String dbName) {

    String url = "jdbc:mysql://" + var.db_host;
    String login = var.db_username;
    String passwd = var.db_psswd;
    Connection cn = null;
    try {
      Class.forName("com.mysql.jdbc.Driver");

      cn = DriverManager.getConnection(url, login, passwd); // Open a connection

      ResultSet resultSet = cn.getMetaData().getCatalogs();

      while (resultSet.next()) {

        String databaseName = resultSet.getString(1);
        if (databaseName.equals(dbName)) {
          return true;
        }
      }
      resultSet.close();

    } catch (Exception e) {
      e.printStackTrace();
    }

    return false;
  }
 private boolean columnExists(Connection connection, String table, String column)
     throws SQLException {
   ResultSet columns = connection.getMetaData().getColumns(null, null, table, column);
   boolean exists = columns.next();
   columns.close();
   return exists;
 }
Example #10
0
 /**
  * čŽ·å–å…ØéƒØč”Ø名äæ”ęÆ
  *
  * @throws SQLException
  */
 private void getTableName() throws SQLException {
   Connection connection = getConnection();
   ResultSet resultSet =
       connection.getMetaData().getTables(null, null, null, new String[] {"TABLE"});
   while (resultSet.next()) {
     tableNameList.add(resultSet.getString(3));
   }
 }
Example #11
0
 public PSqlConnection(Environment env, Connection connection) {
   super(env);
   this.connection = connection;
   try {
     this.metaData = connection.getMetaData();
   } catch (SQLException e) {
     throw new WrapSqlException(env, e);
   }
 }
  /** Creates tables if they do not exist. */
  private void initializeTables() {
    Connection conn = null;
    Statement statement = null;
    try {
      conn = retrieveConnection();
      statement = conn.createStatement();
      statement.setQueryTimeout(30);

      // One table holding the playername id relation
      String playerQuery =
          String.format(
              "CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY AUTOINCREMENT, %s STRING)",
              playerTable, "name");
      statement.executeUpdate(playerQuery);

      // One column for every message
      StringBuilder columns = new StringBuilder();
      for (MessageNode node : MessageNode.getMessageNodes()) {
        MsgCategory cat = messages.getCat(node);
        if (node.getColumnName() != null
            && (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME)) {
          columns.append(',');
          columns.append(node.getColumnName());
        }
      }

      String msgQuery =
          String.format(
              "CREATE TABLE IF NOT EXISTS %s (id INTEGER PRIMARY KEY UNIQUE %s)",
              msgTable, columns);
      statement.executeUpdate(msgQuery);

      // Check if all columns are present
      DatabaseMetaData dmd = conn.getMetaData();
      // Add missing columns
      for (MessageNode node : MessageNode.getMessageNodes()) {
        MsgCategory cat = messages.getCat(node);
        if (cat == MsgCategory.TUTORIAL || cat == MsgCategory.ONE_TIME) {
          ResultSet set = dmd.getColumns(null, null, msgTable, node.getColumnName());
          if (!set.next()) {
            String updateQuery =
                String.format("ALTER TABLE %s ADD COLUMN %s", msgTable, node.getColumnName());
            statement.executeUpdate(updateQuery);
          }
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (conn != null) conn.close();
        if (statement != null) statement.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }
    }
  }
 private List getAllTables(Connection conn) throws SQLException {
   DatabaseMetaData dbMetaData = conn.getMetaData();
   ResultSet rs = dbMetaData.getTables(getCatalog(), getSchema(), null, null);
   List tables = new ArrayList();
   while (rs.next()) {
     tables.add(createTable(conn, rs));
   }
   return tables;
 }
  public synchronized void serialEvent(SerialPortEvent oEvent) {

    try {
      switch (oEvent.getEventType()) {
        case SerialPortEvent.DATA_AVAILABLE:
          if (input == null) {
            System.out.println("here11");
            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
          }
          String inputLine = input.readLine();
          // System.out.println(input.readLine().trim());
          if (inputLine.equals("")) {
          } else {
            String url = "jdbc:mysql://localhost/secureplanet";
            Properties prop = new Properties();
            prop.setProperty("user", "root");
            prop.setProperty("password", "toor");
            Driver d = new com.mysql.jdbc.Driver();
            Connection conn = d.connect(url, prop);
            if (conn == null) {
              System.out.println("connection failed");
              return;
            }
            DatabaseMetaData dm = conn.getMetaData();
            String dbversion = dm.getDatabaseProductVersion();
            String dbname = dm.getDatabaseProductName();
            System.out.println("name:" + dbname);
            System.out.println("version:" + dbversion);

            String rfidtoken = inputLine.trim();
            Statement stmt = conn.createStatement();

            Double lat = 17.4416;
            Double lng = 78.3826;

            String sql =
                "INSERT INTO smarttracking "
                    + "VALUES ('"
                    + rfidtoken
                    + "','"
                    + lat
                    + "','"
                    + lng
                    + "')";
            stmt.executeUpdate(sql);
          }
          break;

        default:
          break;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Example #15
0
 RelProtoDataType getRelDataType(String catalogName, String schemaName, String tableName)
     throws SQLException {
   Connection connection = null;
   try {
     connection = dataSource.getConnection();
     DatabaseMetaData metaData = connection.getMetaData();
     return getRelDataType(metaData, catalogName, schemaName, tableName);
   } finally {
     close(connection, null, null);
   }
 }
Example #16
0
  private String getMainConnName() throws RemoteException {
    String schema = "";
    try {
      Connection connMain = getConnection();
      schema = connMain.getMetaData().getUserName();
      closeConnection(connMain);
    } catch (Exception exc) {
      exc.printStackTrace();
      throw processException(exc);
    }

    return schema;
  }
Example #17
0
 /**
  * Return the first spatial geometry field name
  *
  * @param tableName
  * @param connection
  * @return the name of the first geometry column
  * @throws SQLException
  */
 private static String getFirstGeometryField(String tableName, Connection connection)
     throws SQLException {
   // Find first geometry column
   List<String> geomFields =
       SFSUtilities.getGeometryFields(
           connection,
           TableLocation.parse(tableName, JDBCUtilities.isH2DataBase(connection.getMetaData())));
   if (!geomFields.isEmpty()) {
     return geomFields.get(0);
   } else {
     throw new SQLException("The table " + tableName + " does not contain a geometry field");
   }
 }
Example #18
0
 public static String[] getSchemas(Connection connection) throws Exception {
   if (connection != null) {
     List<String> schemaList = new ArrayList<String>();
     DatabaseMetaData mObject = connection.getMetaData();
     ResultSet schemas = mObject.getSchemas();
     while (schemas.next()) {
       schemaList.add(schemas.getString(DBConstants.DataServiceGenerator.TABLE_SCHEM));
     }
     String str[] = schemaList.toArray(new String[schemaList.size()]);
     return str;
   } else {
     return null;
   }
 }
Example #19
0
  public void readData() {
    try {
      Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
      con =
          DriverManager.getConnection(
              "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=" + filep);
      stmnt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      rst = con.getMetaData().getTables(null, null, "%", null);
      rst.next();
      String SheetName = rst.getString(3);
      String query = "Select distinct * from [" + SheetName + "]";
      rs = stmnt.executeQuery(query);
      if (rs != null) {
        rs.last();
        RowCount = rs.getRow();
        rs.beforeFirst();
        //			 stmnt.close();
        rst.close();
        if (RowCount > 0) {
          registno = new String[RowCount];
          name = new String[RowCount];
          kdno = new int[RowCount];
          kcno = new double[RowCount];
          ccno = new double[RowCount];
          seat = new double[RowCount];
          i = 0;
          while (rs.next() && (rs.getString(1) != null)) {
            //	 rs.next();
            i++;
            try {
              registno[i] = rs.getString(1);
              name[i] = rs.getString(2);
              kdno[i] = Integer.parseInt(rs.getString(3));
              kcno[i] = Double.parseDouble(rs.getString(4));
              ccno[i] = Double.parseDouble(rs.getString(5));
              seat[i] = Double.parseDouble(rs.getString(6));
              System.out.println(i);
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        }
      }
      rs.close();

      con.close();
    } catch (Exception e) {
      //	 System.out.println("fail to get student connection");
    }
  }
Example #20
0
 /**
  * Returns the column types for a given table.
  *
  * @param tableName
  * @param conn
  * @return column types for a given table.
  * @throws SQLException
  */
 public List<String> getColumnTypes(String db, String tableName, Connection conn)
     throws SQLException {
   List<String> columnTypes = new ArrayList<String>(10);
   String schema = null;
   int idx = tableName.indexOf(".");
   if (idx != -1) {
     schema = tableName.substring(0, idx);
     tableName = tableName.substring(idx + 1);
   }
   ResultSet rs = conn.getMetaData().getColumns(db, schema, tableName, null);
   while (rs.next()) {
     columnTypes.add(rs.getString("TYPE_NAME"));
   }
   return columnTypes;
 }
  private Table _getTable(String catalog, String schema, String tableName) throws SQLException {
    if (tableName == null || tableName.trim().length() == 0)
      throw new IllegalArgumentException("tableName must be not empty");
    catalog = StringHelper.defaultIfEmpty(catalog, null);
    schema = StringHelper.defaultIfEmpty(schema, null);

    Connection conn = getConnection();
    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = dbMetaData.getTables(catalog, schema, tableName, null);
    while (rs.next()) {
      Table table = createTable(conn, rs);
      return table;
    }
    return null;
  }
Example #22
0
  // UTILITY
  public boolean hasTable(String tableName) {

    try {
      DatabaseMetaData dbm = connection.getMetaData();
      ResultSet tables = dbm.getTables(null, null, tableName, null);
      while (tables.next()) {
        String foundName = tables.getString("TABLE_NAME");
        if (tableName.equals(foundName)) {
          return true;
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return false;
  }
Example #23
0
  boolean tiene_tablas() {
    DatabaseMetaData dbmd = null;
    Integer contador = 0;
    try {
      dbmd = conexion.getMetaData();
      String[] tipo = {"TABLE"};
      ResultSet rs = dbmd.getTables(null, null, "%", tipo);
      while (rs.next()) {
        contador++;
      }
    } catch (SQLException e) {
      System.out.println("Error al obtener informaciĆ³n de la bd...");
    }

    return contador > 0;
  }
Example #24
0
  @Override
  public ArrayList<String> getListOfTables(Connection conn)
      throws SQLException, ClassNotFoundException {

    ArrayList<String> tableNames = new ArrayList<String>();
    DatabaseMetaData dmd = conn.getMetaData();
    // Pedro: 2012/12/03 comment out to enable loading Views in Karma (on behalf of Maria)
    // ResultSet rs = dmd.getTables(null, null, null, new String[] {"TABLE"});
    ResultSet rs = dmd.getTables(null, null, null, new String[] {"TABLE", "VIEW"});
    while (rs.next()) {
      String tablename = rs.getString(3);
      String schema = rs.getString(2);
      if (schema != null && schema.length() > 0) tableNames.add(schema + "." + tablename);
      else tableNames.add(tablename);
    }
    Collections.sort(tableNames);
    return tableNames;
  }
 private Connection createDatasource() throws ClassNotFoundException, SQLException {
   Connection connection = getConnection();
   boolean exist = false;
   int tableNameColumn = 3;
   DatabaseMetaData dbm = connection.getMetaData();
   for (ResultSet rs = dbm.getTables(null, null, null, null); rs.next(); ) {
     if (rs.getString(tableNameColumn).equals(TABLE_NAME)) {
       exist = true;
       rs.close();
       break;
     }
   }
   if (!exist) {
     Statement statement = connection.createStatement();
     statement.executeUpdate(
         "CREATE TABLE " + TABLE_NAME + " (name VARCHAR(32) PRIMARY KEY, balance FLOAT)");
   }
   return connection;
 }
Example #26
0
  private void loadDatabaseMetadata() {
    if (!databaseMetadataLoaded) {
      String componentName = "UNKNOWN";
      Connection con = null;
      try {
        componentName = getMetaComponent().getName();

        con = DataSourceConnectionProvider.getByComponent(componentName).getConnection();
        DatabaseMetaData metaData = con.getMetaData();
        supportsSchemasInDataManipulation = metaData.supportsSchemasInDataManipulation();
        Collection timeDateFunctions =
            Strings.toCollection(metaData.getTimeDateFunctions().toUpperCase());

        //
        // another solution instead of the use of 'if' would be to use a xml with
        //	the information of the functions from each BBDD
        if ("DB2 UDB for AS/400".equals(metaData.getDatabaseProductName())
            || "Oracle".equals(metaData.getDatabaseProductName())
            || "PostgresSQL".equals(metaData.getDatabaseProductName())) {
          supportsTranslateFunction = true;
        }
        if ("Oracle".equals(metaData.getDatabaseProductName())
            || "PostgreSQL".equals(metaData.getDatabaseProductName())) {
          supportsYearFunction = supportsMonthFunction = false;
        } else {
          supportsYearFunction = timeDateFunctions.contains("YEAR");
          supportsMonthFunction = timeDateFunctions.contains("MONTH");
        }
        databaseMetadataLoaded = true;
      } catch (Exception ex) {
        log.warn(XavaResources.getString("load_database_metadata_warning"));
      } finally {
        try {
          if (con != null) {
            con.close();
          }
        } catch (SQLException e) {
          log.warn(XavaResources.getString("close_connection_warning"));
        }
      }
    }
  }
Example #27
0
  public static void main(String args[]) {
    try {
      Class.forName("org.gjt.mm.mysql.Driver");

      Connection con =
          DriverManager.getConnection("jdbc:mysql://localhost:3333/world", "root", "root");

      DatabaseMetaData dbmd = con.getMetaData();
      String table[] = {"TABLE"};
      ResultSet rs = dbmd.getTables(null, null, null, table);

      while (rs.next()) {
        System.out.println(rs.getString(3));
      }

      con.close();

    } catch (Exception e) {
      System.out.println(e);
    }
  }
Example #28
0
 private static Map<PwmAboutProperty, String> getConnectionDebugProperties(
     final Connection connection) {
   if (connection != null) {
     try {
       final Map<PwmAboutProperty, String> returnObj = new LinkedHashMap<>();
       final DatabaseMetaData databaseMetaData = connection.getMetaData();
       returnObj.put(PwmAboutProperty.database_driverName, databaseMetaData.getDriverName());
       returnObj.put(PwmAboutProperty.database_driverVersion, databaseMetaData.getDriverVersion());
       returnObj.put(
           PwmAboutProperty.database_databaseProductName,
           databaseMetaData.getDatabaseProductName());
       returnObj.put(
           PwmAboutProperty.database_databaseProductVersion,
           databaseMetaData.getDatabaseProductVersion());
       return Collections.unmodifiableMap(returnObj);
     } catch (SQLException e) {
       LOGGER.error("error rading jdbc meta data: " + e.getMessage());
     }
   }
   return Collections.emptyMap();
 }
 public List getIdentityTables() {
   // delete all the data in the jbpm tables
   List jbpmTableNames = new ArrayList();
   try {
     createConnection();
     ResultSet resultSet = connection.getMetaData().getTables("", "", null, null);
     while (resultSet.next()) {
       String tableName = resultSet.getString("TABLE_NAME");
       if ((tableName != null)
           && (tableName.length() > 5)
           && (IDENTITY_TABLE_PREFIX.equalsIgnoreCase(tableName.substring(0, 5)))) {
         jbpmTableNames.add(tableName);
       }
     }
   } catch (SQLException e) {
     throw new RuntimeException("couldn't get the jbpm table names");
   } finally {
     closeConnection();
   }
   return jbpmTableNames;
 }
Example #30
0
  static void truncateTable(String strTable) {

    String DBMS = "";
    try {
      DatabaseMetaData metaData = conn.getMetaData();
      DBMS = metaData.getDatabaseProductName().toLowerCase();
    } catch (SQLException e) {
      System.out.println("Problem determining database product name: " + e);
    }
    System.out.println("Truncating '" + strTable + "' ...");
    try {
      if (DBMS.startsWith("db2")) {
        stmt.execute("TRUNCATE TABLE " + strTable + " IMMEDIATE");
      } else {
        stmt.execute("TRUNCATE TABLE " + strTable);
      }
      transCommit();
    } catch (SQLException se) {
      System.out.println(se.getMessage());
      transRollback();
    }
  }