from DatabaseLiaison
771960
public boolean renameColumn (Connection conn, String table, String from, String to,
                                 ColumnDefinition newColumnDef) throws SQLException
    {
        executeQuery(conn, "ALTER TABLE " + tableSQL(table) + " RENAME COLUMN " +
                     columnSQL(from) + " TO " + columnSQL(to));
        log("Renamed column '" + from + "' on table '" + table + "' to '" + to + "'");
        return true;
    }
301801
@Override
   public ValidationErrors validate(final DropSpatialIndexStatement statement,
         final Database database, final SqlGeneratorChain sqlGeneratorChain) {
      final ValidationErrors validationErrors = new ValidationErrors();
      validationErrors.checkRequiredField("tableName", statement.getTableName());
      return validationErrors;
   }
697615
@Override
   public SqlStatement[] generateStatements(final Database database) {
      final Collection<SqlStatement> statements = new ArrayList<SqlStatement>();
      // MySQL and PostgreSQL only need the normal DROP INDEX statement.
      if (!(database instanceof MySQLDatabase) && !(database instanceof PostgresDatabase)) {
         final DropSpatialIndexStatement dropSpatialIndex = new DropSpatialIndexStatement(
               this.indexName, this.catalogName, this.schemaName, this.tableName);
         statements.add(dropSpatialIndex);
      }

      // GeoDB doesn't use a tradition index structure so don't issue the normal DROP INDEX
      // statement.
      if (!(database instanceof DerbyDatabase) && !(database instanceof H2Database)) {
         final DropIndexStatement dropIndex = new DropIndexStatement(this.indexName,
               this.catalogName, this.schemaName, this.tableName, null);
         statements.add(dropIndex);
      }
      return statements.toArray(new SqlStatement[statements.size()]);
   }
1155496
function(conn) {
    var coll = CollMethods.Instance(dbLit, conn);
    var dbMethods = DBMethods(dbLit, conn);
    var dbMethodKeys = Object.keys(dbMethods);

    return {
      getOwnPropertyNames: function() {
        conn.db.collectionNames(conn.flow.add());

        return conn.flow.wait().map(function(obj) {
          var collName = obj.name;
          return collName.substr(collName.indexOf('.') + 1);
        }).concat(dbMethodKeys.map(function(methodName) {
          return util.format('%s(', methodName);
        }));
      },
      getOwnPropertyDescriptor: function(proxy, collectionName) {
        return {
          writable: false,
          enumerable: false,
          configurable: true
        };
      },
      getPropertyDescriptor: function(proxy, collectionName) {
        return this.getOwnPropertyDescriptor(proxy, collectionName);
      },
      get: function(proxy, op1) {
        if (op1 === 'getConn') {
          return function() { return conn; };
        } else if (op1 === '_name') {
          return conn.db.databaseName;
        } else if (op1 === 'toString') {
          return function() { return conn.db.databaseName; };
        }

        if (dbMethodKeys.indexOf(op1) !== -1) {
          return dbMethods[op1];
        }

        var collOps = coll(op1);
        var collOpKeys = Object.keys(collOps);
        var _this = this;
        return Proxy.create({
          getOwnPropertyNames: function() {
            var collNames = _this.getOwnPropertyNames();
            var matchColls = collNames.filter(function(collName) {
              return collName !== op1 &&
                collName.indexOf(op1) !== -1;
            }).map(function(collName) {
              var ext = collName.substr(collName.indexOf('.') + 1);
              var subExt = ext.indexOf(op1);
              if (subExt != -1) {
                return '';
              }
              return ext;
            }).filter(function(collName) {
              return collName.length;
            });
            if (matchColls.length) {
              return matchColls;
            }
            return collOpKeys.map(function(collOpKey) {
              return util.format('%s(', collOpKey);
            });
          },
          getOwnPropertyDescriptor: function(proxy, op) {
            return _this.getOwnPropertyDescriptor(proxy, op);
          },
          getPropertyDescriptor: function(proxy, op) {
            return _this.getPropertyDescriptor(proxy, op);
          },
          get: function(proxy, op2) {
            if (collOpKeys.indexOf(op2) !== -1) {
              return collOps[op2];
            }
            return _this.get(proxy, op1 + '.' + op2);
          }
        });
      }
    };
  }
1302172
@Then("^a Mongo dataBase '(.+?)' contains a table '(.+?)' with values:")
    public void assertValuesOfTableMongo(String dataBase, String tableName, DataTable data) {
        commonspec.getMongoDBClient().connectToMongoDBDataBase(dataBase);
        ArrayList<DBObject> result = (ArrayList<DBObject>) commonspec.getMongoDBClient().readFromMongoDBCollection(
                tableName, data);
        DBObjectsAssert.assertThat(result).containedInMongoDBResult(data);

    }
641104
def doSQLInsert(sqlString)
   
      sql = sqlString.dup
      dbname = ""
      state = nil
      fieldName = ""
      fieldValue = ""
      fieldNames = []
      fieldValues = []
      index = 0
      
      clearFieldValuePairList
      
      sql.gsub!("("," ")
      sql.gsub!(")"," ")

      sql.split(' ').each{ |token|
         case token
            when "INSERT", "INTO" 
               state = "getTable"
               next
            when "VALUES" 
               state = "getFieldValue"
               next
         end
         if state == "getTable"
            dbname = token.strip
            state =   "getFieldName"
         elsif state  == "getFieldName" 
            fieldName = token.dup
            fieldName.gsub!("],","")
            fieldName.gsub!('[','')
            fieldName.gsub!(']','')
            fieldName.gsub!(',','')
            fieldNames << fieldName
         elsif state  == "getFieldValue" 
            test = token.dup
            if test[-1,1] == "'" or test[-2,2] == "',"
               fieldValue << token.dup
               if fieldValue[-2,2] == "',"
                  fieldValue.gsub!("',",'')
               end
               fieldValue.gsub!('\'','')
               if fieldValue.length > 0 and fieldNames[index] 
                  addFieldValuePair(fieldNames[index],nil,nil,fieldValue)
                  fieldName = ""
                  fieldValue = ""
               end
               index += 1
            elsif token == ","
               addFieldValuePair(fieldNames[index],nil,nil,"")
               fieldName = ""
               fieldValue = ""
               index += 1
            else
               fieldValue << "#{token.dup} "
            end
         end
      }
      
      if dbname and @dbid.nil?
         dbid = findDBByname( dbname )
      else
         dbid = lookupChdbid( dbname )
      end
      dbid ||= @dbid

      recordid = nil
      if dbid
         recordid,updateid = addRecord(dbid,@fvlist)
      end   
      recordid
      
   end
978619
public static String execSqlQueryTabular(@NotNull final SQLInputs sqlInputs) throws Exception {
        ConnectionService connectionService = new ConnectionService();
        try (final Connection connection = connectionService.setUpConnection(sqlInputs)){
            connection.setReadOnly(true);

            final Statement statement = connection.createStatement(sqlInputs.getResultSetType(), sqlInputs.getResultSetConcurrency());
            statement.setQueryTimeout(sqlInputs.getTimeout());

            final ResultSet resultSet = statement.executeQuery(sqlInputs.getSqlCommand());

            final String resultSetToTable = Format.resultSetToTable(resultSet, sqlInputs.isNetcool());
            resultSet.close();
            return resultSetToTable;
        }
    }
69748
void getProperties(Connection connection, long id, LoggingEvent event)
      throws SQLException {

    PreparedStatement statement = connection.prepareStatement(sqlProperties);
    try {
      statement.setLong(1, id);
      ResultSet rs = statement.executeQuery();

      while (rs.next()) {
        String key = rs.getString(1);
        String value = rs.getString(2);
        event.setProperty(key, value);
      }
    } finally {
      statement.close();
    }
  }
431981
protected void getMySqlEngine(Map<String, String> dbPoolData) {

        String engine = "MYISAM";
        CmsSetupDb setupDb = new CmsSetupDb(null);
        CmsSetupDBWrapper db = null;
        try {
            setupDb.setConnection(
                dbPoolData.get("driver"),
                dbPoolData.get("url"),
                dbPoolData.get("params"),
                dbPoolData.get("user"),
                dbPoolData.get("pwd"));

            db = setupDb.executeSqlStatement("SHOW TABLE STATUS LIKE 'CMS_GROUPS';", null);
            if (db.getResultSet().next()) {
                engine = db.getResultSet().getString("Engine").toUpperCase();
            }

        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (db != null) {
                db.close();
            }
            setupDb.closeConnection();
        }
        dbPoolData.put("engine", engine);
        System.out.println("Table engine:               " + engine);
    }
615399
static List<String> getAllTables(String database, Statement stmt) throws SQLException {
        List<String> table = new ArrayList<>();
        ResultSet rs;
        rs = stmt.executeQuery("SHOW TABLE STATUS FROM `" + database + "`;");
        while ( rs.next() ) {
            table.add(rs.getString("Name"));
        }
        return table;
    }
148990
public void init(DatabaseOwner databaseOwner, String strDbName, int iDatabaseType, Map<String, Object> properties)
    {
        super.init(databaseOwner, strDbName, iDatabaseType, properties);
        m_pDatabase = null;
    }
967664
def from_set(cls, database, key, data, clear=False):
        
        s = cls(database, key)
        if clear:
            s.clear()
        s.add(*data)
        return s
1225753
private String determineDatabaseProductName(Connection conn) {
        try {
            final String databaseProductName = conn.getMetaData().getDatabaseProductName().toLowerCase();
            LOGGER.debug("Database product: {}", databaseProductName);
            return databaseProductName;
        } catch (SQLException se) {
            LOGGER.warn("Problem determining database product!", se);
            return null;
        }
    }
974644
private void prepareStatements() throws DatabaseException {
        for (PreparedStatementCveDb key : values()) {
            PreparedStatement preparedStatement = null;
            try {
                final String statementString = statementBundle.getString(key.name());
                if (key == INSERT_VULNERABILITY || key == INSERT_CPE) {
                    preparedStatement = connection.prepareStatement(statementString, new String[]{"id"});
                } else {
                    preparedStatement = connection.prepareStatement(statementString);
                }
            } catch (SQLException ex) {
                throw new DatabaseException(ex);
            } catch (MissingResourceException ex) {
                if (!ex.getMessage().contains("key MERGE_PROPERTY")) {
                    throw new DatabaseException(ex);
                }
            }
            if (preparedStatement != null) {
                preparedStatements.put(key, preparedStatement);
            }
        }
    }
550367
@Override
    public void check(Connection conn, String scName, Collection<String> tbNames) throws IllegalMetaDataException {
        if (scName == null) {
            throw new IllegalArgumentException("[Check MetaData Failed] parameter 'scName' can't be null");
        }
        if (tbNames == null || tbNames.isEmpty()) {
            throw new IllegalArgumentException("[Check MetaData Failed] parameter 'tbNames' can't be empty");
        }
        try {
            Set<String> set = getAllTables(conn, scName);
            if (set == null || set.isEmpty()) {
                throw new IllegalMetaDataException(
                                                   "[Check MetaData Failed] Schema:'"
                                                           + scName
                                                           + "' has nothing tables. but in your configuration it requires table:"
                                                           + DDRJSONUtils.toJSONString(tbNames));
            }
            for (String tbName : tbNames) {
                if (!set.contains(tbName)) {
                    throw new IllegalMetaDataException("[Check MetaData Failed] Schema:'" + scName
                                                       + "' only has tables:" + DDRJSONUtils.toJSONString(set)
                                                       + ", but in your configuration it requires table:" + tbName);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
644898
public DatabaseInfo getDatabaseInfo(Connection connection) throws SQLException
    {
        PreparedStatement statement = connection.prepareStatement("select @@servername, db_name()");
        ResultSet results = null;
        DatabaseInfo info = null;

        try
        {
            results = statement.executeQuery();

            if (!results.next())
            {
                throw new SQLException("Query for database name and server name returned zero rows!");
            }

            info = new DatabaseInfo(results.getString(1), results.getString(2));
        }
        finally
        {
            closeResultSet(results, "Ignoring error whilst closing ResultSet that was used to query the DatabaseInfo");

            closeStatement(statement, "Ignoring error whilst closing PreparedStatement that was used to query the DatabaseInfo");
        }

        return info;
    }
1049659
private void createTables(Connection conn) throws DatabaseException {
        LOGGER.debug("Creating database structure");

        try (InputStream is = FileUtils.getResourceAsStream(DB_STRUCTURE_RESOURCE)) {
            final String dbStructure = IOUtils.toString(is, StandardCharsets.UTF_8);

            Statement statement = null;
            try {
                statement = conn.createStatement();
                statement.execute(dbStructure);
            } catch (SQLException ex) {
                LOGGER.debug("", ex);
                throw new DatabaseException("Unable to create database statement", ex);
            } finally {
                DBUtils.closeStatement(statement);
            }
        } catch (IOException ex) {
            throw new DatabaseException("Unable to create database schema", ex);
        }
    }