Java Code Examples for java.sql.ResultSetMetaData

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

Example 1

From project safe, under directory /Safe/src/org/openintents/safe/.

Source file: CSVWriter.java

  24 
vote

/** 
 * Writes the entire ResultSet to a CSV file. The caller is responsible for closing the ResultSet.
 * @param rs the recordset to write
 * @param includeColumnNames true if you want column names in the output, false otherwise
 */
public void writeAll(java.sql.ResultSet rs,boolean includeColumnNames) throws SQLException, IOException {
  ResultSetMetaData metadata=rs.getMetaData();
  if (includeColumnNames) {
    writeColumnNames(metadata);
  }
  int columnCount=metadata.getColumnCount();
  while (rs.next()) {
    String[] nextLine=new String[columnCount];
    for (int i=0; i < columnCount; i++) {
      nextLine[i]=getColumnValue(rs,metadata.getColumnType(i + 1),i + 1);
    }
    writeNext(nextLine);
  }
}
 

Example 2

From project BeeQueue, under directory /src/org/beequeue/util/.

Source file: JsonTable.java

  22 
vote

public static String queryToJson(ResultSet rs,String title,String parent,String drill) throws SQLException {
  ResultSetMetaData md=rs.getMetaData();
  List<Object> header=buildHeader(md);
  List<List<Object>> data=buildData(rs,header);
  rs.close();
  return new JsonTable(title,parent,drill,header,data).toJsonTable();
}
 

Example 3

From project codjo-control, under directory /codjo-control-common/src/test/java/net/codjo/control/common/loader/.

Source file: TransfertDataTest.java

  22 
vote

private void mockMetadataStuff() throws SQLException {
  Statement statement4Metadadta=mock(Statement.class);
  resultSet4Metadata=mock(ResultSet.class);
  ResultSetMetaData resultSetMetadata=mock(ResultSetMetaData.class);
  when(connection.createStatement()).thenReturn(statement4Metadadta);
  String metadataQuery="select * from QUARANTINE where 1 = 0";
  when(statement4Metadadta.executeQuery(metadataQuery)).thenReturn(resultSet4Metadata);
  when(statement4Metadadta.executeQuery(not(eq(metadataQuery)))).thenThrow(new SQLException("Unexpected query has been detected -> != " + metadataQuery));
  when(resultSet4Metadata.getMetaData()).thenReturn(resultSetMetadata);
  when(resultSetMetadata.getColumnCount()).thenReturn(3);
  when(resultSetMetadata.getColumnLabel(1)).thenReturn("QUARANTINE_ID");
  when(resultSetMetadata.getColumnLabel(2)).thenReturn("TOTO_COL");
  when(resultSetMetadata.getColumnLabel(3)).thenReturn("TiTi_COL");
}
 

Example 4

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

Source file: SQLUtilCopyTable.java

  22 
vote

static List<String> listColumnNamesOfATable(Connection connection,String table) throws SQLException {
  List<String> fields=new ArrayList<String>();
  ResultSet columnsResultSet=connection.createStatement().executeQuery(VarsCompiler.compile(METADATA_SQL,"table",table));
  ResultSetMetaData setMetaData=columnsResultSet.getMetaData();
  for (int colIndex=1; colIndex <= setMetaData.getColumnCount(); colIndex++) {
    fields.add(setMetaData.getColumnName(colIndex));
  }
  columnsResultSet.close();
  return fields;
}
 

Example 5

From project convertcsv, under directory /ConvertCSV/src/org/openintents/convertcsv/opencsv/.

Source file: CSVWriter.java

  22 
vote

/** 
 * Writes the entire ResultSet to a CSV file. The caller is responsible for closing the ResultSet.
 * @param rs the recordset to write
 * @param includeColumnNames true if you want column names in the output, false otherwise
 */
public void writeAll(java.sql.ResultSet rs,boolean includeColumnNames) throws SQLException, IOException {
  ResultSetMetaData metadata=rs.getMetaData();
  if (includeColumnNames) {
    writeColumnNames(metadata);
  }
  int columnCount=metadata.getColumnCount();
  while (rs.next()) {
    String[] nextLine=new String[columnCount];
    for (int i=0; i < columnCount; i++) {
      nextLine[i]=getColumnValue(rs,metadata.getColumnType(i + 1),i + 1);
    }
    writeNext(nextLine);
  }
}
 

Example 6

From project core_1, under directory /src/com/iCo6/util/org/apache/commons/dbutils/.

Source file: BasicRowProcessor.java

  22 
vote

/** 
 * Convert a <code>ResultSet</code> row into an <code>Object[]</code>. This implementation copies column values into the array in the same  order they're returned from the <code>ResultSet</code>.  Array elements will be set to <code>null</code> if the column was SQL NULL.
 * @see org.apache.commons.dbutils.RowProcessor#toArray(java.sql.ResultSet)
 * @param rs ResultSet that supplies the array data
 * @throws SQLException if a database access error occurs
 * @return the newly created array
 */
public Object[] toArray(ResultSet rs) throws SQLException {
  ResultSetMetaData meta=rs.getMetaData();
  int cols=meta.getColumnCount();
  Object[] result=new Object[cols];
  for (int i=0; i < cols; i++) {
    result[i]=rs.getObject(i + 1);
  }
  return result;
}
 

Example 7

From project CraftCommons, under directory /src/main/java/com/craftfire/commons/database/.

Source file: Results.java

  22 
vote

public Results(String query,ResultSet rs) throws SQLException {
  this.query=query;
  this.array=new ArrayList<DataRow>();
  ResultSetMetaData metaData=rs.getMetaData();
  this.rows=metaData.getColumnCount();
  while (rs.next()) {
    DataRow data=new DataRow();
    for (int i=1; i <= this.rows; i++) {
      data.add(new DataField(i,rs));
    }
    this.array.add(data);
  }
}
 

Example 8

From project db2triples, under directory /src/main/java/net/antidot/semantic/rdf/rdb2rdf/r2rml/core/.

Source file: R2RMLEngine.java

  22 
vote

private ResultSetMetaData extractMetaDatas(ResultSet rows2) throws SQLException {
  ResultSetMetaData meta=rows.getMetaData();
  Set<String> columnsNames=new HashSet<String>();
  for (int i=1; i <= meta.getColumnCount(); i++) {
    String columnName=meta.getColumnLabel(i);
    if (!columnsNames.contains(columnName))     columnsNames.add(columnName);
 else     throw new SQLException("[R2RMLEngine:extractMetaDatas] duplicate column names in the " + "SELECT list of the SQL query");
  }
  return meta;
}
 

Example 9

From project Diver, under directory /ca.uvic.chisel.javasketch.data/src/ca/uvic/chisel/javasketch/data/model/imple/internal/.

Source file: TraceModelIDImpl.java

  22 
vote

/** 
 * Loads attributes into this model implementation based on the column names stored within the results set.
 * @param results
 * @throws SQLException if there was an error retrieving the results.
 */
protected final void loadFromResults(ResultSet results) throws SQLException {
  if (results == null)   return;
  ResultSetMetaData md=results.getMetaData();
  for (int i=1; i <= md.getColumnCount(); i++) {
    setDataValue(md.getColumnName(i),results.getObject(i));
  }
}
 

Example 10

From project jdonframework, under directory /JdonAccessory/src/com/jdon/model/query/.

Source file: JdbcUtil.java

  22 
vote

/** 
 * return a List in the List, every object is a map, by database column name, we can get the its result from map
 * @param rs ResultSet
 * @return List
 * @throws Exception
 */
public List extract(ResultSet rs) throws Exception {
  ResultSetMetaData meta=rs.getMetaData();
  int count=meta.getColumnCount();
  List ret=new ArrayList();
  while (rs.next()) {
    Map map=new LinkedHashMap(count);
    for (int i=1; i <= count; i++) {
      map.put(meta.getColumnName(i),rs.getObject(i));
    }
    ret.add(map);
  }
  return ret;
}
 

Example 11

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

Source file: DbAccess.java

  22 
vote

private ShellTable printResult(ResultSet rs) throws SQLException {
  ShellTable table=new ShellTable();
  ResultSetMetaData meta=rs.getMetaData();
  for (int c=1; c <= meta.getColumnCount(); c++) {
    table.header.add(meta.getColumnLabel(c));
  }
  while (rs.next()) {
    List<String> row=table.addRow();
    for (int c=1; c <= meta.getColumnCount(); c++) {
      row.add(rs.getString(c));
    }
  }
  return table;
}
 

Example 12

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/executor/jvm/.

Source file: ColumnMapRowMapper.java

  22 
vote

public Object mapRow(ResultSet rs,int rowNum) throws SQLException {
  ResultSetMetaData rsmd=rs.getMetaData();
  int columnCount=rsmd.getColumnCount();
  Map mapOfColValues=createColumnMap(columnCount);
  for (int i=1; i <= columnCount; i++) {
    String key=getColumnKey(rsmd.getColumnName(i));
    Object obj=getColumnValue(rs,i);
    mapOfColValues.put(key,obj);
  }
  return mapOfColValues;
}
 

Example 13

From project medsavant, under directory /MedSavantServerEngine/src/org/ut/biolab/medsavant/db/util/.

Source file: DBUtil.java

  22 
vote

public DbTable importTable(String sessionId,String tablename) throws SQLException {
  DbSpec spec=new DbSpec();
  DbSchema schema=spec.addDefaultSchema();
  DbTable table=schema.addTable(tablename);
  ResultSet rs=ConnectionController.executeQuery(sessionId,"DESCRIBE " + tablename);
  ResultSetMetaData rsMetaData=rs.getMetaData();
  int numberOfColumns=rsMetaData.getColumnCount();
  while (rs.next()) {
    table.addColumn(rs.getString(1),getColumnTypeString(rs.getString(2)),getColumnLength(rs.getString(2)));
  }
  return table;
}
 

Example 14

From project opencsv, under directory /test/au/com/bytecode/opencsv/.

Source file: MockResultSetMetaDataBuilder.java

  22 
vote

public static ResultSetMetaData buildMetaData(String[] columnNames) throws SQLException {
  ResultSetMetaData metaData=Mockito.mock(ResultSetMetaData.class);
  Mockito.when(metaData.getColumnCount()).thenReturn(columnNames.length);
  for (int i=0; i < columnNames.length; i++) {
    Mockito.when(metaData.getColumnName(i + 1)).thenReturn(columnNames[i]);
    Mockito.when(metaData.getColumnType(i + 1)).thenReturn(Types.VARCHAR);
  }
  return metaData;
}
 

Example 15

From project org.openscada.aurora, under directory /org.openscada.utils.osgi.jdbc/src/org/openscada/utils/osgi/jdbc/data/.

Source file: SingleColumnRowMapper.java

  22 
vote

@Override public void validate(final ResultSet resultSet) throws RowMapperValidationException, SQLException {
  final ResultSetMetaData md=resultSet.getMetaData();
  if (md.getColumnCount() != 1) {
    throw new RowMapperValidationException("Column count must be exactly one");
  }
}
 

Example 16

From project RoyalCommands, under directory /src/org/royaldev/royalcommands/opencsv/.

Source file: ResultSetHelperService.java

  22 
vote

public String[] getColumnNames(ResultSet rs) throws SQLException {
  List<String> names=new ArrayList<String>();
  ResultSetMetaData metadata=rs.getMetaData();
  for (int i=0; i < metadata.getColumnCount(); i++) {
    names.add(metadata.getColumnName(i + 1));
  }
  String[] nameArray=new String[names.size()];
  return names.toArray(nameArray);
}
 

Example 17

From project saiku, under directory /saiku-core/saiku-service/src/test/java/org/saiku/.

Source file: AbstractServiceUtils.java

  22 
vote

public static void dump(ResultSet rs) throws SQLException {
  ResultSetMetaData meta=rs.getMetaData();
  int colmax=meta.getColumnCount();
  int i;
  Object o=null;
  for (; rs.next(); ) {
    for (i=0; i < colmax; ++i) {
      o=rs.getObject(i + 1);
      System.out.print(o.toString() + " ");
    }
    System.out.println(" ");
  }
}
 

Example 18

From project SORMA, under directory /sorma/sorma-test/src/main/java/com/gaoshin/sorma/test/.

Source file: ResultSetCursor.java

  22 
vote

@Override public String getColumnName(int columnIndex){
  try {
    ResultSetMetaData metaData=rs.getMetaData();
    String name=metaData.getColumnName(columnIndex);
    return name;
  }
 catch (  SQLException e) {
    throw new RuntimeException(e);
  }
}
 

Example 19

From project TadpoleForDBTools, under directory /com.hangum.db.commons.sql/src/com/hangum/tadpole/commons/sql/util/.

Source file: SQLUtil.java

  22 
vote

/** 
 * metadata? ?????? ???? ??? ???? ??????.
 * @param rs
 * @return index???? ????
 */
public static HashMap<Integer,String> mataDataToMap(ResultSet rs) throws Exception {
  HashMap<Integer,String> map=new HashMap<Integer,String>();
  ResultSetMetaData rsm=rs.getMetaData();
  int columnCount=rsm.getColumnCount();
  for (int i=0; i < columnCount; i++) {
    map.put(i,rsm.getColumnLabel(i + 1));
  }
  return map;
}
 

Example 20

From project trademaker, under directory /src/org/lifeform/db/.

Source file: Test.java

  22 
vote

public static void dump(final ResultSet rs) throws SQLException {
  ResultSetMetaData meta=rs.getMetaData();
  int colmax=meta.getColumnCount();
  int i;
  Object o=null;
  for (; rs.next(); ) {
    for (i=0; i < colmax; ++i) {
      o=rs.getObject(i + 1);
      System.out.print(o.toString() + " ");
    }
    System.out.println(" ");
  }
}
 

Example 21

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

Source file: MetaDataTestCase.java

  22 
vote

/** 
 * Utility method to check column names and number.
 * @param rs    the result set to check
 * @param names the list of column names to compare to result set
 * @return the <code>boolean</code> value true if the columns match
 */
protected boolean checkColumnNames(ResultSet rs,String[] names) throws SQLException {
  ResultSetMetaData rsmd=rs.getMetaData();
  if (rsmd.getColumnCount() < names.length) {
    System.out.println("Cols=" + rsmd.getColumnCount());
    return false;
  }
  for (int i=1; i <= names.length; i++) {
    if (names[i - 1].length() > 0 && !rsmd.getColumnLabel(i).equals(names[i - 1])) {
      System.out.println(names[i - 1] + " = " + rsmd.getColumnLabel(i));
      return false;
    }
  }
  return true;
}
 

Example 22

From project webframe, under directory /wf-web-page/src/main/java/org/webframe/web/page/adapter/map/.

Source file: HashMapAdapter.java

  22 
vote

/** 
 * @see org.webframe.web.page.adapter.jdbc.AbstractJdbcAdapter#processResultSet(java.lang.String,java.sql.ResultSet,int,org.webframe.web.page.ValueListInfo)
 */
@Override public List<Map<String,Object>> processResultSet(String name,ResultSet result,int numberPerPage,ValueListInfo info) throws SQLException {
  List<Map<String,Object>> ret=new ArrayList<Map<String,Object>>(numberPerPage);
  ResultSetMetaData meta=result.getMetaData();
  Map<String,Object> m;
  int columnCount=meta.getColumnCount();
  for (int i=0; i < numberPerPage && result.next(); i++) {
    m=new HashMap<String,Object>(columnCount);
    for (int j=1; j <= columnCount; j++) {
      m.put(meta.getColumnLabel(j),result.getObject(j));
    }
    ret.add(m);
  }
  return ret;
}
 

Example 23

From project zen-project, under directory /zen-jsweb/src/main/java/com/nominanuda/jsweb/host/.

Source file: JdbcDataSource.java

  22 
vote

public DataObject mapRow(ResultSet rs,int rowNum) throws SQLException {
  DataObjectImpl o=new DataObjectImpl();
  ResultSetMetaData rsMetaData=rs.getMetaData();
  int numberOfColumns=rsMetaData.getColumnCount();
  for (int i=1; i < numberOfColumns + 1; i++) {
    String name=rsMetaData.getColumnName(i);
    Object tval=convertToNative(rs,name);
    o.put(name,tval);
  }
  return o;
}
 

Example 24

From project activejdbc, under directory /activejdbc/src/main/java/org/javalite/activejdbc/.

Source file: RowProcessor.java

  21 
vote

protected void processRS(RowListener listener) throws SQLException {
  ResultSetMetaData metaData=rs.getMetaData();
  String labels[]=new String[metaData.getColumnCount()];
  for (int i=1; i <= labels.length; i++) {
    labels[i - 1]=metaData.getColumnLabel(i);
  }
  while (rs.next()) {
    HashMap<String,Object> row=new HashMap<String,Object>();
    for (    String label : labels) {
      row.put(label.toLowerCase(),rs.getObject(label));
    }
    if (!listener.next(row))     break;
  }
  rs.close();
  s.close();
}
 

Example 25

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageSchema/.

Source file: DatabaseDefn.java

  21 
vote

/** 
 * Attempts to read the first 10 records from a given report, to check there isn't an error in the SQL
 */
private void throwExceptionIfDbViewIsBroken(Connection conn,BaseReportInfo report) throws SQLException, ObjectNotFoundException, CodingErrorException, CantDoThatException {
  PreparedStatement statement=null;
  try {
    ReportData.enableOptimisations(conn,report,true);
    String SQLCode="SELECT * FROM " + report.getInternalReportName() + " LIMIT 10";
    statement=conn.prepareStatement(SQLCode);
    ResultSet testResults=statement.executeQuery();
    ResultSetMetaData metaData=testResults.getMetaData();
    int numColumns=metaData.getColumnCount();
    while (testResults.next()) {
      for (int i=1; i <= numColumns; i++) {
        String testKey=testResults.getString(i);
      }
    }
    testResults.close();
    statement.close();
    ReportData.enableOptimisations(conn,report,false);
  }
 catch (  SQLException sqlex) {
    throw new SQLException("The requested change would cause an error in the report: " + sqlex.getMessage() + ". SQL = "+ statement,sqlex.getSQLState(),sqlex);
  }
}
 

Example 26

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

Source file: FindSqlGenerator.java

  21 
vote

public Match mapRow(ResultSet rs,int rowNum) throws SQLException {
  Match match=new Match();
  ResultSetMetaData metaData=rs.getMetaData();
  int columnCount=metaData.getColumnCount();
  String node_name=null;
  List<String> corpus_path=null;
  for (int column=1; column <= columnCount; ++column) {
    if (metaData.getColumnName(column).startsWith("path_name")) {
      corpus_path=corpusPathExtractor.extractCorpusPath(rs,metaData.getColumnName(column));
    }
  }
  for (int column=1; column <= columnCount; ++column) {
    if (metaData.getColumnName(column).startsWith("node_name")) {
      node_name=rs.getString(column);
    }
 else     if (rs.wasNull()) {
      break;
    }
    if (node_name != null) {
      match.setSaltId(buildSaltId(corpus_path,node_name));
      node_name=null;
    }
  }
  return match;
}
 

Example 27

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

Source file: TableOperations.java

  21 
vote

public static ArrayList<Map<String,String>> select(Connection con,String table,Map<String,String> conditions){
  Statement stm=createStatement(con);
  ArrayList<Map<String,String>> result=new ArrayList<Map<String,String>>();
  try {
    ResultSet rs=stm.executeQuery(SQLQueryBuilder.createSelect(table,conditions));
    ResultSetMetaData meta;
    while (rs.next()) {
      meta=rs.getMetaData();
      HashMap<String,String> temp=new HashMap<String,String>();
      for (int i=0; i < meta.getColumnCount(); i++) {
        temp.put(meta.getColumnLabel(i + 1),rs.getString(i + 1));
      }
      result.add(temp);
    }
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
  return result;
}
 

Example 28

From project autopsy, under directory /RecentActivity/src/org/sleuthkit/autopsy/recentactivity/.

Source file: Extract.java

  21 
vote

/** 
 * Returns a List of FsContent objects from TSK based on sql query.
 * @param rs is the resultset that needs to be converted to an arraylist
 * @return  list returns the arraylist built from the converted resultset
 */
public List<HashMap<String,Object>> resultSetToArrayList(ResultSet rs) throws SQLException {
  ResultSetMetaData md=rs.getMetaData();
  int columns=md.getColumnCount();
  List<HashMap<String,Object>> list=new ArrayList<HashMap<String,Object>>(50);
  while (rs.next()) {
    HashMap<String,Object> row=new HashMap<String,Object>(columns);
    for (int i=1; i <= columns; ++i) {
      if (rs.getObject(i) == null) {
        row.put(md.getColumnName(i),"");
      }
 else {
        row.put(md.getColumnName(i),rs.getObject(i));
      }
    }
    list.add(row);
  }
  return list;
}
 

Example 29

From project Blitz, under directory /src/com/laxser/blitz/lama/core/.

Source file: BeanPropertyRowMapper.java

  21 
vote

/** 
 * Extract the values for all columns in the current row. <p> Utilizes public setters and result set metadata.
 * @see java.sql.ResultSetMetaData
 */
public Object mapRow(ResultSet rs,int rowNumber) throws SQLException {
  Object mappedObject=instantiateClass(this.mappedClass);
  BeanWrapper bw=new BeanWrapperImpl(mappedObject);
  ResultSetMetaData rsmd=rs.getMetaData();
  int columnCount=rsmd.getColumnCount();
  boolean warnEnabled=logger.isWarnEnabled();
  boolean debugEnabled=logger.isDebugEnabled();
  Set<String> populatedProperties=(checkProperties ? new HashSet<String>() : null);
  for (int index=1; index <= columnCount; index++) {
    String column=JdbcUtils.lookupColumnName(rsmd,index).toLowerCase();
    PropertyDescriptor pd=this.mappedFields.get(column);
    if (pd != null) {
      try {
        Object value=JdbcUtils.getResultSetValue(rs,index,pd.getPropertyType());
        if (debugEnabled && rowNumber == 0) {
          logger.debug("Mapping column '" + column + "' to property '"+ pd.getName()+ "' of type "+ pd.getPropertyType());
        }
        bw.setPropertyValue(pd.getName(),value);
        if (populatedProperties != null) {
          populatedProperties.add(pd.getName());
        }
      }
 catch (      NotWritablePropertyException ex) {
        throw new DataRetrievalFailureException("Unable to map column " + column + " to property "+ pd.getName(),ex);
      }
    }
 else {
      if (checkColumns) {
        throw new InvalidDataAccessApiUsageException("Unable to map column '" + column + "' to any properties of bean "+ this.mappedClass.getName());
      }
      if (warnEnabled && rowNumber == 0) {
        logger.warn("Unable to map column '" + column + "' to any properties of bean "+ this.mappedClass.getName());
      }
    }
  }
  if (populatedProperties != null && !populatedProperties.equals(this.mappedProperties)) {
    throw new InvalidDataAccessApiUsageException("Given ResultSet does not contain all fields " + "necessary to populate object of class [" + this.mappedClass + "]: "+ this.mappedProperties);
  }
  return mappedObject;
}
 

Example 30

From project caustic, under directory /console/src/net/caustic/database/.

Source file: JDBCSqliteConnection.java

  21 
vote

@Override public boolean doesTableHaveColumn(String tableName,String columnName) throws SQLConnectionException {
  try {
    commit();
    boolean result=false;
    ResultSet rs=getResultSet("SELECT * FROM `" + tableName + "`",new String[]{});
    ResultSetMetaData meta=rs.getMetaData();
    int numCol=meta.getColumnCount();
    for (int i=1; i < numCol + 1; i++) {
      if (meta.getColumnName(i).equals(columnName)) {
        result=true;
      }
    }
    rs.close();
    return result;
  }
 catch (  SQLException e) {
    throw new SQLConnectionException(e);
  }
}
 

Example 31

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

Source file: JdbcFixture.java

  21 
vote

public static void dumpResultSet(ResultSet resultSet,Writer outWriter) throws SQLException {
  PrintWriter out=new PrintWriter(outWriter);
  ResultSetMetaData rsmd=resultSet.getMetaData();
  int colmumnCount=rsmd.getColumnCount();
  for (int i=1; i <= colmumnCount; i++) {
    out.print("\"" + rsmd.getColumnName(i) + "\"");
    if (i + 1 <= colmumnCount) {
      out.print(", ");
    }
  }
  out.println();
  while (resultSet.next()) {
    for (int i=1; i <= colmumnCount; i++) {
      out.print("\"" + resultSet.getObject(i) + "\"");
      if (i + 1 <= colmumnCount) {
        out.print(", ");
      }
    }
    out.println();
  }
}
 

Example 32

From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/plugin/.

Source file: ExpressionCompilerCommand.java

  21 
vote

private void findSourceColumnType(XmlFamilyPreference familyPreference,Map<String,Integer> sourceColumn,List<String> usedSourceColumns) throws UnknownVariableException, SQLException {
  QueryBuilder builder=QueryBuilderFactory.newSelectQueryBuilder(new QueryConfigWithoutWhereClause(familyPreference.getSelectConfig()));
  List<String> fields=new ArrayList<String>(usedSourceColumns);
  if (familyPreference.hasFilter()) {
    RowFilter filter=familyPreference.getFilter();
    fields.add(SegmentationUtil.determineFullColumnName(filter.getTableName(),filter.getColumnName()));
  }
  String selectQuery=SegmentationUtil.buildSelectQuery(builder,fields,Collections.<String,String>emptyMap(),new DefaultFieldInfoList());
  Statement statement=getContext().getConnection().createStatement();
  try {
    ResultSet resultSet=statement.executeQuery(selectQuery);
    ResultSetMetaData metaData=resultSet.getMetaData();
    for (int i=0; i < usedSourceColumns.size(); i++) {
      sourceColumn.put(usedSourceColumns.get(i),metaData.getColumnType(i + 1));
    }
  }
  finally {
    statement.close();
  }
}
 

Example 33

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

Source file: TestEnvironnement.java

  21 
vote

/** 
 * Description of the Method
 * @param con       Description of the Parameter
 * @param tableName Description of the Parameter
 * @throws SQLException Description of the Exception
 */
public static void spoolTable(Connection con,String tableName) throws SQLException {
  Statement stmt=con.createStatement();
  APP.debug("******************** SPOOL de " + tableName + "********************");
  try {
    ResultSet rs=stmt.executeQuery("select * from " + tableName);
    ResultSetMetaData rsmd=rs.getMetaData();
    int colmumnCount=rsmd.getColumnCount();
    String strColmumnCount="";
    for (int i=1; i <= colmumnCount; i++) {
      strColmumnCount+="\t" + rsmd.getColumnName(i);
    }
    APP.debug(strColmumnCount);
    strColmumnCount="";
    for (int i=1; i <= colmumnCount; i++) {
      strColmumnCount+="\t" + rsmd.getColumnTypeName(i);
    }
    APP.debug(strColmumnCount);
    strColmumnCount="";
    while (rs.next()) {
      for (int i=1; i <= colmumnCount; i++) {
        strColmumnCount+="\t" + rs.getObject(i);
      }
      APP.debug(strColmumnCount);
    }
  }
  finally {
    stmt.close();
  }
}
 

Example 34

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

Source file: ReflectionMapper.java

  21 
vote

public void mapResultSet(ResultSet resultSet,T bean) throws Exception {
  Class<? extends DBObject> clazz=bean.getClass();
  Table table=clazz.getAnnotation(Table.class);
  TableField[] tableFields=table.field();
  ResultSetMetaData rsmd=resultSet.getMetaData();
  int numberOfColumns=rsmd.getColumnCount();
  for (int i=1; i <= numberOfColumns; i++) {
    String name=rsmd.getColumnName(i);
    TableField tableField=searchTableField(tableFields,name);
    if (tableField == null)     continue;
    String fieldName=tableField.field().length() == 0 ? tableField.name() : tableField.field();
    Field field=getField(clazz,fieldName);
    if (field == null)     continue;
    ReflectionUtil.setValue(bean,field,getValue(rsmd.getColumnType(i),resultSet,name));
  }
}
 

Example 35

From project datavalve, under directory /datavalve-sql/src/main/java/org/fluttercode/datavalve/provider/jdbc/.

Source file: TableRow.java

  21 
vote

/** 
 * A static factory method that creates and initializes a TableRow instance for the current row of the passed in  {@link ResultSet}.
 * @param resultSet The  {@link ResultSet} containing the values we need to loadinto the TableRow instance.
 * @return a new TableRow instance initialized with the values from the{@link ResultSet}.
 */
public static TableRow createTableRowFromResultSet(ResultSet resultSet){
  TableRow result=new TableRow();
  try {
    ResultSetMetaData metadata=resultSet.getMetaData();
    for (int i=0; i < metadata.getColumnCount(); i++) {
      int colIndex=i + 1;
      String name=metadata.getColumnName(colIndex);
      Object value=resultSet.getObject(colIndex);
      result.add(name,value);
    }
  }
 catch (  SQLException exception) {
    exception.printStackTrace();
  }
  return result;
}
 

Example 36

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

Source file: QueryExecutor.java

  21 
vote

public static List<Map<String,Object>> executeLoopQuery(Connection connection,String query,Object[] parameters) throws Exception {
  Statement stmt=null;
  PreparedStatement pstmt=null;
  ArrayList array=new ArrayList();
  ResultSet results;
  if (parameters == null) {
    stmt=connection.createStatement();
    results=stmt.executeQuery(query);
  }
 else {
    pstmt=connection.prepareStatement(query);
    for (int i=0; i < parameters.length; i++) {
      pstmt.setObject(i + 1,parameters[i]);
    }
    results=pstmt.executeQuery();
  }
  ResultSetMetaData meta=results.getMetaData();
  while (results.next()) {
    HashMap<String,Object> h=new HashMap<String,Object>(meta.getColumnCount());
    for (int i=1; i <= meta.getColumnCount(); i++) {
      Object ob=results.getObject(i);
      h.put(meta.getColumnLabel(i).toUpperCase(),ob);
    }
    array.add(h);
  }
  results.close();
  if (stmt != null) {
    stmt.close();
  }
  if (pstmt != null) {
    pstmt.close();
  }
  return array;
}
 

Example 37

From project dolphin, under directory /texcel/src/com/tan/excel/util/.

Source file: DBUtil.java

  21 
vote

/** 
 * ???????????.
 * @param tableName
 */
public void select(String tableName){
  this.init();
  try {
    pstmt=connection.prepareStatement("SELECT * FROM " + tableName);
    rs=pstmt.executeQuery();
    ResultSetMetaData meta=rs.getMetaData();
    int columnCount=meta.getColumnCount();
    printColumns(columnCount,meta);
    meta=null;
    while (rs.next()) {
      for (int i=1; i <= columnCount; i++) {
        Object o=rs.getObject(i);
        if (i == 1)         print(o,'\t',(short)0);
        print(o,'\t',(short)1);
      }
      System.out.println();
    }
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
  this.dispose();
}
 

Example 38

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

Source file: CodeGenParser.java

  21 
vote

/** 
 * Adds DBColumn object to the given DBTable. The DBColumn is created from the given ResultSet
 */
private DBTableColumn addColumn(DBTable t,ResultSet rs) throws SQLException {
  String name=rs.getString("COLUMN_NAME");
  DataType empireType=getEmpireDataType(rs.getInt("DATA_TYPE"));
  double colSize=Double.parseDouble("" + rs.getInt("COLUMN_SIZE") + '.'+ rs.getInt("DECIMAL_DIGITS"));
  boolean required=false;
  String defaultValue=rs.getString("COLUMN_DEF");
  if (rs.getString("IS_NULLABLE").equalsIgnoreCase("NO"))   required=true;
  if (rs.getInt("DATA_TYPE") == Types.TIMESTAMP && defaultValue != null && defaultValue.equals("CURRENT_TIMESTAMP")) {
    required=false;
    defaultValue=null;
  }
  DataType originalType=empireType;
  ResultSetMetaData metaData=rs.getMetaData();
  int colCount=metaData.getColumnCount();
  String colName;
  for (int i=1; i <= colCount; i++) {
    colName=metaData.getColumnName(i);
    if ((colName.equalsIgnoreCase("IS_AUTOINCREMENT") && rs.getString(i).equalsIgnoreCase("YES")) || (colName.equals("TYPE_NAME") && rs.getString(i).matches(".*(?i:identity).*"))) {
      empireType=DataType.AUTOINC;
    }
  }
  log.info("\tCOLUMN:\t" + name + " ("+ empireType+ ")");
  DBTableColumn col=t.addColumn(name,empireType,colSize,required,defaultValue);
  if (empireType.equals(DataType.AUTOINC))   col.setAttribute("AutoIncDataType",originalType);
  return col;
}
 

Example 39

From project GeoBI, under directory /webapp/src/main/java/com/c2c/controller/.

Source file: GetCubeProperties.java

  21 
vote

private JSONArray executeGetMembers(String cube,String dimension) throws MalformedURLException, IOException {
  MembersQuery qGm=getQueryFactory().createMembersQuery(cube,dimension);
  ResultSet membersSet=qGm.execute();
  try {
    JSONArray jsRet=new JSONArray();
    ResultSetMetaData mdSet=membersSet.getMetaData();
    while (membersSet.next()) {
      Hashtable<String,String> membersMap=new Hashtable<String,String>();
      membersMap.put(mdSet.getColumnName(9),membersSet.getString(9));
      membersMap.put(mdSet.getColumnName(10),membersSet.getString(10));
      membersMap.put(mdSet.getColumnName(7),membersSet.getString(7));
      membersMap.put(mdSet.getColumnName(16),membersSet.getString(16));
      jsRet.add(membersMap);
    }
    return jsRet;
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
  return null;
}
 

Example 40

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

Source file: DatabaseMetaDataSupportImpl.java

  21 
vote

/** 
 * Returns the columns of the specified table.
 * @param metaData a DatabaseMetaData implementation
 * @param table a schema qualified table name
 * @return a Map of column name to column properties
 * @throws SQLException if an error occurs access DatabaseMetaData
 */
@Override public Map<String,ColumnProperties> getColumns(DatabaseMetaData metaData,QualifiedName table) throws SQLException {
  Statement statement=metaData.getConnection().createStatement();
  try {
    Map<String,ColumnProperties> columnMap=new HashMap<String,ColumnProperties>();
    ResultSetMetaData resultSet=statement.executeQuery(String.format("SELECT * FROM %s WHERE 0=1",table.getDMLName())).getMetaData();
    for (int i=1; i <= resultSet.getColumnCount(); ++i) {
      String column=this.quote(resultSet.getColumnName(i));
      int type=resultSet.getColumnType(i);
      String nativeType=resultSet.getColumnTypeName(i);
      boolean autoIncrement=resultSet.isAutoIncrement(i);
      columnMap.put(column,new ColumnPropertiesImpl(column,type,nativeType,null,null,autoIncrement));
    }
    return columnMap;
  }
  finally {
    Resources.close(statement);
  }
}
 

Example 41

From project hiho, under directory /src/co/nubetech/hiho/mapreduce/lib/db/.

Source file: GenericDBOutputFormat.java

  21 
vote

public static void setOutput(Job job,String tableName,String columnNames) throws IOException {
  job.setOutputFormatClass(GenericDBOutputFormat.class);
  DBConfiguration dbConf=new DBConfiguration(job.getConfiguration());
  dbConf.setOutputTableName(tableName);
  dbConf.setOutputFieldNames(columnNames);
  String dbDriver=job.getConfiguration().get(DBConfiguration.DRIVER_CLASS_PROPERTY);
  String connString=job.getConfiguration().get(DBConfiguration.URL_PROPERTY);
  String username=job.getConfiguration().get(DBConfiguration.USERNAME_PROPERTY);
  String password=job.getConfiguration().get(DBConfiguration.PASSWORD_PROPERTY);
  Connection conn;
  PreparedStatement stmt;
  try {
    Class.forName(dbDriver).newInstance();
    conn=DriverManager.getConnection(connString,username,password);
    String query="select " + columnNames + " from "+ tableName;
    stmt=conn.prepareStatement(query);
    ResultSetMetaData meta=stmt.getMetaData();
    ArrayList<ColumnInfo> columnInfo=populateColumnInfo(meta);
    String jsonString=getJsonStringOfColumnInfo(columnInfo);
    job.getConfiguration().set(HIHOConf.COLUMN_INFO,jsonString);
    logger.debug("columnInfo is: " + job.getConfiguration().get(HIHOConf.COLUMN_INFO));
    stmt.close();
    conn.close();
  }
 catch (  Exception e) {
    e.printStackTrace();
    throw new IOException(e);
  }
}
 

Example 42

From project jboss-jstl-api_spec, under directory /src/main/java/javax/servlet/jsp/jstl/sql/.

Source file: ResultImpl.java

  21 
vote

/** 
 * This constructor reads the ResultSet and saves a cached copy. It's important to note that this object will be serializable only if the objects returned by the ResultSet are serializable too.
 * @param rs an open <tt>ResultSet</tt>, positioned before the firstrow
 * @param startRow beginning row to be cached
 * @param maxRows query maximum rows limit
 * @exception java.sql.SQLException if a database error occurs
 */
public ResultImpl(ResultSet rs,int startRow,int maxRows) throws SQLException {
  rowMap=new ArrayList();
  rowByIndex=new ArrayList();
  ResultSetMetaData rsmd=rs.getMetaData();
  int noOfColumns=rsmd.getColumnCount();
  columnNames=new String[noOfColumns];
  for (int i=1; i <= noOfColumns; i++) {
    columnNames[i - 1]=rsmd.getColumnName(i);
  }
  for (int i=0; i < startRow; i++) {
    rs.next();
  }
  int processedRows=0;
  while (rs.next()) {
    if ((maxRows != -1) && (processedRows == maxRows)) {
      isLimited=true;
      break;
    }
    Object[] columns=new Object[noOfColumns];
    SortedMap columnMap=new TreeMap(String.CASE_INSENSITIVE_ORDER);
    for (int i=1; i <= noOfColumns; i++) {
      Object value=rs.getObject(i);
      if (rs.wasNull()) {
        value=null;
      }
      columns[i - 1]=value;
      columnMap.put(columnNames[i - 1],value);
    }
    rowMap.add(columnMap);
    rowByIndex.add(columns);
    processedRows++;
  }
}
 

Example 43

From project jdbi, under directory /src/main/java/org/skife/jdbi/v2/.

Source file: DefaultMapper.java

  21 
vote

public Map<String,Object> map(int index,ResultSet r,StatementContext ctx){
  Map<String,Object> row=new DefaultResultMap();
  ResultSetMetaData m;
  try {
    m=r.getMetaData();
  }
 catch (  SQLException e) {
    throw new ResultSetException("Unable to obtain metadata from result set",e,ctx);
  }
  try {
    for (int i=1; i <= m.getColumnCount(); i++) {
      String key=m.getColumnName(i);
      String alias=m.getColumnLabel(i);
      Object value=r.getObject(i);
      row.put(alias != null ? alias : key,value);
    }
  }
 catch (  SQLException e) {
    throw new ResultSetException("Unable to access specific metadata from " + "result set metadata",e,ctx);
  }
  return row;
}
 

Example 44

From project l2jserver2, under directory /l2jserver2-common/src/main/java/com/l2jserver/service/database/ddl/.

Source file: TableFactory.java

  21 
vote

/** 
 * Reads an table from the database and returns the parsed object. <p> Note that this method does not parse everything: default values, enum types, primary and foreign keys are not parsed.
 * @param conn the JDBC  {@link Connection}
 * @param template the query template
 * @param tableName the table name
 * @return the parsed table
 * @throws SQLException if any sql error occur
 */
public static Table createTable(Connection conn,QueryTemplate template,String tableName) throws SQLException {
  Statement st=conn.createStatement();
  try {
    st.execute(new StringBuilder(template.getSelect()).append("*").append(template.getFrom()).append(template.quoteIdentifier(tableName)).toString());
    final ResultSet rs=st.getResultSet();
    ResultSetMetaData metaData=rs.getMetaData();
    final Map<String,Column> columns=CollectionFactory.newMap();
    for (int i=1; i <= metaData.getColumnCount(); i++) {
      columns.put(metaData.getColumnName(i),new Column(metaData.getColumnName(i),getColumnType(metaData.getColumnType(i)),false,metaData.getColumnDisplaySize(i),false,null));
    }
    return new Table(metaData.getTableName(1),columns,null,null);
  }
  finally {
    st.close();
  }
}
 

Example 45

From project mmoCore, under directory /src/main/java/mmo/Core/SQLibrary/.

Source file: DatabaseHandler.java

  21 
vote

/** 
 * This converts the next (first) row from a ResultSet into a simple HashMap. You can call this repeatedly on the same ResultSet to parse every row.
 * @param result the ResultSet to convert
 * @return a simple Map of the first row
 */
protected Map<String,Object> ResultSetToMap(ResultSet result){
  Map<String,Object> output=new HashMap<String,Object>();
  try {
    if (result != null && result.next()) {
      ResultSetMetaData mtd=result.getMetaData();
      for (int i=mtd.getColumnCount(); i > 0; i--) {
        output.put(mtd.getColumnLabel(i),result.getObject(i));
        writeInfo(mtd.getColumnLabel(i) + " -> " + result.getObject(i));
      }
    }
  }
 catch (  SQLException e) {
    writeError("ResultSetToMap Error: " + e.getMessage(),false);
  }
  return output;
}
 

Example 46

From project neo4j-jdbc, under directory /src/test/java/org/neo4j/jdbc/.

Source file: Neo4jQueryNodeTest.java

  21 
vote

@Test public void testRetrieveNodes() throws SQLException {
  createData(gdb);
  Statement stmt=conn.createStatement();
  ResultSet rs=stmt.executeQuery("start n=node(*) match p=n-[r?]-m return n,r,m,p,ID(n),length(p),n.name? as name limit 5");
  int count=0;
  ResultSetMetaData metaData=rs.getMetaData();
  int cols=metaData.getColumnCount();
  Assert.assertThat(cols,is(7));
  while (rs.next()) {
    for (int i=1; i <= cols; i++) {
      System.out.print(rs.getObject(i) + "\t");
    }
    System.out.println();
    count++;
  }
  Assert.assertThat(count,is(5));
}
 

Example 47

From project ontology-broker, under directory /src/org/sc/probro/data/.

Source file: DBObject.java

  21 
vote

public void setFromResultSet(ResultSet rs) throws SQLException {
  ResultSetMetaData data=rs.getMetaData();
  for (int i=1; i <= data.getColumnCount(); i++) {
    String columnName=data.getColumnName(i).toLowerCase();
    try {
      Field f=getClass().getField(columnName);
      int mod=f.getModifiers();
      if (Modifier.isPublic(mod) && !Modifier.isStatic(mod)) {
        Object value=rs.getObject(i);
        if (value instanceof Clob) {
          Clob clob=(Clob)value;
          f.set(this,readClob(clob));
        }
 else         if (value instanceof java.sql.Date) {
          java.sql.Date sqlDate=(java.sql.Date)value;
          long time=sqlDate.getTime();
          java.util.Date date=new java.util.Date(time);
          f.set(this,date);
        }
 else {
          f.set(this,value);
        }
      }
    }
 catch (    NoSuchFieldException e) {
    }
catch (    IllegalAccessException e) {
      e.printStackTrace(System.err);
    }
  }
}
 

Example 48

From project OpenSettlers, under directory /src/java/soc/server/database/.

Source file: SOCDBHelper.java

  21 
vote

private static void dispResultSet(ResultSet rs) throws SQLException {
  System.out.println("dispResultSet()");
  int i;
  ResultSetMetaData rsmd=rs.getMetaData();
  int numCols=rsmd.getColumnCount();
  for (i=1; i <= numCols; i++) {
    if (i > 1) {
      System.out.print(",");
    }
    System.out.print(rsmd.getColumnLabel(i));
  }
  System.out.println("");
  boolean more=rs.next();
  while (more) {
    for (i=1; i <= numCols; i++) {
      if (i > 1) {
        System.out.print(",");
      }
      System.out.print(rs.getString(i));
    }
    System.out.println("");
    more=rs.next();
  }
}
 

Example 49

From project PenguinCMS, under directory /PenguinCMS/tests/vendor/sahi/src/net/sf/sahi/plugin/.

Source file: DBClient.java

  21 
vote

ArrayList<ArrayList<String>> getResult(final String driverName,final String jdbcurl,final String username,final String password,final String sql) throws ClassNotFoundException, SQLException {
  ClassLoadHelper.getClass(driverName);
  Connection connection=DriverManager.getConnection(jdbcurl,username,password);
  Statement stmt=connection.createStatement();
  ArrayList<ArrayList<String>> list=new ArrayList<ArrayList<String>>();
  try {
    ResultSet rs=stmt.executeQuery(sql);
    ArrayList<String> columnNames=new ArrayList<String>();
    ResultSetMetaData rsmd=rs.getMetaData();
    int numColumns=rsmd.getColumnCount();
    for (int i=1; i < numColumns + 1; i++) {
      String columnName=rsmd.getColumnName(i);
      columnNames.add(columnName);
    }
    list.add(columnNames);
    while (rs.next()) {
      ArrayList<String> record=new ArrayList<String>();
      for (Iterator<String> iterator=columnNames.iterator(); iterator.hasNext(); ) {
        String columnName=iterator.next();
        String value=rs.getString(columnName);
        record.add(value);
      }
      list.add(record);
    }
  }
  finally {
    if (connection != null) {
      try {
        connection.close();
      }
 catch (      Exception e) {
      }
    }
  }
  return list;
}
 

Example 50

From project pepe, under directory /jdt-derby-proxy/src/main/java/edu/stanford/pepe/jdt/.

Source file: SQLRead.java

  21 
vote

private Fingerprint computeFingerprint(PepeResultSet rs) throws SQLException {
  final ByteArrayOutputStream baos=new ByteArrayOutputStream();
  final DataOutputStream os=new DataOutputStream(baos);
  final ResultSetMetaData metadata=rs.getMetaData();
  final int columns=metadata.getColumnCount();
  try {
    while (rs.next()) {
      os.writeUTF("<result>");
      for (int column=1; column < columns; column++) {
        os.writeUTF("<column" + column + ">");
        write(rs,os,column,metadata.getColumnType(column));
      }
    }
  }
 catch (  IOException e) {
    throw new RuntimeException("Unexpected, who could be throwing an IO exception?",e);
  }
  return computeFingerprint(baos);
}
 

Example 51

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

Source file: GeneratedKeysH2Test.java

  21 
vote

@Test public void test() throws SQLException {
  stmt.execute("drop table GENERATED_KEYS if exists");
  stmt.execute("create table GENERATED_KEYS(" + "ID int AUTO_INCREMENT PRIMARY KEY, " + "NAME varchar(30))");
  QGeneratedKeysEntity entity=new QGeneratedKeysEntity("entity");
  SQLInsertClause insertClause=new SQLInsertClause(conn,new H2Templates(),entity);
  ResultSet rs=insertClause.set(entity.name,"Hello").executeWithKeys();
  ResultSetMetaData md=rs.getMetaData();
  System.out.println(md.getColumnName(1));
  assertTrue(rs.next());
  assertEquals(1,rs.getInt(1));
  assertFalse(rs.next());
  insertClause=new SQLInsertClause(conn,new H2Templates(),entity);
  rs=insertClause.set(entity.name,"World").executeWithKeys();
  assertTrue(rs.next());
  assertEquals(2,rs.getInt(1));
  assertFalse(rs.next());
  insertClause=new SQLInsertClause(conn,new H2Templates(),entity);
  assertEquals(3,insertClause.set(entity.name,"World").executeWithKey(entity.id).intValue());
  insertClause=new SQLInsertClause(conn,new H2Templates(),entity);
  assertEquals(Collections.singletonList(4),insertClause.set(entity.name,"World").executeWithKeys(entity.id));
}
 

Example 52

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

Source file: TableFactory.java

  21 
vote

public Table createTable(ResultSet rs) throws SQLException {
  long start=System.currentTimeMillis();
  String tableName=null;
  try {
    ResultSetMetaData rsMetaData=rs.getMetaData();
    String schemaName=rs.getString("TABLE_SCHEM") == null ? "" : rs.getString("TABLE_SCHEM");
    tableName=rs.getString("TABLE_NAME");
    String tableType=rs.getString("TABLE_TYPE");
    String remarks=rs.getString("REMARKS");
    if (remarks == null && DatabaseMetaDataUtils.isOracleDataBase(connection.getMetaData())) {
      remarks=getOracleTableComments(tableName);
    }
    Table table=new Table();
    table.setSchema(schema);
    table.setCatalog(catalog);
    table.setSqlName(tableName);
    table.setRemarks(remarks);
    if ("SYNONYM".equals(tableType) && DatabaseMetaDataUtils.isOracleDataBase(connection.getMetaData())) {
      String[] ownerAndTableName=getSynonymOwnerAndTableName(tableName);
      table.setOwnerSynonymName(ownerAndTableName[0]);
      table.setTableSynonymName(ownerAndTableName[1]);
    }
    retriveTableColumns(table);
    table.initExportedKeys(connection.getMetaData());
    table.initImportedKeys(connection.getMetaData());
    BeanHelper.copyProperties(table,TableOverrideValuesProvider.getTableConfigValues(table.getSqlName()));
    return table;
  }
 catch (  SQLException e) {
    throw new RuntimeException("create table object error,tableName:" + tableName,e);
  }
 finally {
    GLogger.perf("createTable() cost:" + (System.currentTimeMillis() - start) + " tableName:"+ tableName);
  }
}
 

Example 53

From project SimpleSave, under directory /src/main/java/com/alta189/simplesave/sqlite/.

Source file: SQLiteDatabase.java

  21 
vote

public void checkTableStructure(TableRegistration table){
  StringBuilder query=new StringBuilder();
  query.append("SELECT * FROM ").append(table.getName()).append(" LIMIT 1");
  try {
    ResultSetMetaData meta=connection.prepareStatement(query.toString()).executeQuery().getMetaData();
    Collection<FieldRegistration> fields=table.getFields();
    Map<String,String> redo=new LinkedHashMap<String,String>();
    for (    FieldRegistration f : fields) {
      boolean found=false;
      String deftype=SQLiteUtil.getSQLiteTypeFromClass(f.getType());
      for (int i=1; i <= meta.getColumnCount(); i++) {
        if (f.getName().equalsIgnoreCase(meta.getColumnName(i))) {
          found=true;
          break;
        }
      }
      if (!found) {
        redo.put(f.getName(),false + ";" + deftype);
      }
    }
    for (    String s : redo.keySet()) {
      StringBuilder q=new StringBuilder();
      String[] results=redo.get(s).split(";");
      q.append("ALTER TABLE ").append(table.getName()).append(" ");
      q.append("ADD COLUMN ").append(s).append(" ").append(results[1]);
      connection.prepareStatement(q.toString()).executeUpdate();
    }
  }
 catch (  SQLException e) {
    e.printStackTrace();
  }
}
 

Example 54

From project spring-data-jdbc-ext, under directory /spring-data-oracle/src/main/java/org/springframework/data/jdbc/support/oracle/.

Source file: BeanPropertyStructMapper.java

  21 
vote

public STRUCT toStruct(T source,Connection conn,String typeName) throws SQLException {
  StructDescriptor descriptor=new StructDescriptor(typeName,conn);
  ResultSetMetaData rsmd=descriptor.getMetaData();
  int columns=rsmd.getColumnCount();
  Object[] values=new Object[columns];
  for (int i=1; i <= columns; i++) {
    String column=JdbcUtils.lookupColumnName(rsmd,i).toLowerCase();
    PropertyDescriptor fieldMeta=(PropertyDescriptor)this.mappedFields.get(column);
    if (fieldMeta != null) {
      BeanWrapper bw=new BeanWrapperImpl(source);
      if (bw.isReadableProperty(fieldMeta.getName())) {
        try {
          if (logger.isDebugEnabled()) {
            logger.debug("Mapping column named \"" + column + "\""+ " to property \""+ fieldMeta.getName()+ "\"");
          }
          values[i - 1]=bw.getPropertyValue(fieldMeta.getName());
        }
 catch (        NotReadablePropertyException ex) {
          throw new DataRetrievalFailureException("Unable to map column " + column + " to property "+ fieldMeta.getName(),ex);
        }
      }
 else {
        logger.warn("Unable to access the getter for " + fieldMeta.getName() + ".  Check that "+ "get"+ StringUtils.capitalize(fieldMeta.getName())+ " is declared and has public access.");
      }
    }
  }
  STRUCT struct=new STRUCT(descriptor,conn,values);
  return struct;
}
 

Example 55

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

Source file: SqlManager.java

  21 
vote

protected Map<String,String> getColumnTypeNamesForRawQuery(String stmt){
  ResultSet results;
  try {
    results=execute(stmt);
  }
 catch (  SQLException sqlE) {
    LOG.error("Error executing statement: " + sqlE.toString(),sqlE);
    release();
    return null;
  }
  try {
    Map<String,String> colTypeNames=new HashMap<String,String>();
    int cols=results.getMetaData().getColumnCount();
    ResultSetMetaData metadata=results.getMetaData();
    for (int i=1; i < cols + 1; i++) {
      String colTypeName=metadata.getColumnTypeName(i);
      String colName=metadata.getColumnName(i);
      if (colName == null || colName.equals("")) {
        colName=metadata.getColumnLabel(i);
      }
      colTypeNames.put(colName,colTypeName);
    }
    return colTypeNames;
  }
 catch (  SQLException sqlException) {
    LOG.error("Error reading from database: " + sqlException.toString());
    return null;
  }
 finally {
    try {
      results.close();
      getConnection().commit();
    }
 catch (    SQLException sqlE) {
      LOG.warn("SQLException closing ResultSet: " + sqlE.toString());
    }
    release();
  }
}
 

Example 56

From project trugger, under directory /src/main/java/org/atatec/trugger/element/impl/.

Source file: ResultSetElementFinder.java

  21 
vote

@Override public Result<Set<Element>,Object> findAll(){
  return new Result<Set<Element>,Object>(){
    @Override public Set<Element> in(    Object target){
      if (target instanceof Class<?>) {
        return Collections.emptySet();
      }
      Set<Element> elements=new HashSet<Element>();
      ResultSet resultSet=(ResultSet)target;
      try {
        ResultSetMetaData metaData=resultSet.getMetaData();
        for (int i=1; i <= metaData.getColumnCount(); i++) {
          elements.add(new SpecificElement(new ResultSetElement(metaData.getColumnName(i)),resultSet));
        }
      }
 catch (      SQLException e) {
        throw new RuntimeException(e);
      }
      return elements;
    }
  }
;
}
 

Example 57

From project twistDemo, under directory /twist-libs/com.thoughtworks.webdriver.recorder_1.0.0.11288/sahi/src/net/sf/sahi/plugin/.

Source file: DBClient.java

  21 
vote

ArrayList<ArrayList<String>> getResult(final String driverName,final String jdbcurl,final String username,final String password,final String sql) throws ClassNotFoundException, SQLException {
  ClassLoadHelper.getClass(driverName);
  Connection connection=DriverManager.getConnection(jdbcurl,username,password);
  Statement stmt=connection.createStatement();
  ArrayList<ArrayList<String>> list=new ArrayList<ArrayList<String>>();
  try {
    ResultSet rs=stmt.executeQuery(sql);
    ArrayList<String> columnNames=new ArrayList<String>();
    ResultSetMetaData rsmd=rs.getMetaData();
    int numColumns=rsmd.getColumnCount();
    for (int i=1; i < numColumns + 1; i++) {
      String columnName=rsmd.getColumnName(i);
      columnNames.add(columnName);
    }
    list.add(columnNames);
    while (rs.next()) {
      ArrayList<String> record=new ArrayList<String>();
      for (Iterator<String> iterator=columnNames.iterator(); iterator.hasNext(); ) {
        String columnName=iterator.next();
        String value=rs.getString(columnName);
        record.add(value);
      }
      list.add(record);
    }
  }
  finally {
    if (connection != null) {
      try {
        connection.close();
      }
 catch (      Exception e) {
      }
    }
  }
  return list;
}
 

Example 58

From project utils_1, under directory /src/main/java/net/pterodactylus/util/database/.

Source file: MapCreator.java

  21 
vote

/** 
 * @see net.pterodactylus.util.database.ObjectCreator#createObject(java.sql.ResultSet)
 */
@Override public Map<String,Object> createObject(ResultSet resultSet) throws SQLException {
  Map<String,Object> result=new HashMap<String,Object>();
  ResultSetMetaData metadata=resultSet.getMetaData();
  for (int column=1; column <= metadata.getColumnCount(); column++) {
    int columnType=metadata.getColumnType(column);
    String columnLabel=metadata.getColumnLabel(column);
    if (columnType == Types.INTEGER) {
      result.put(columnLabel,resultSet.getInt(column));
    }
 else     if (columnType == Types.BIGINT) {
      result.put(columnLabel,resultSet.getLong(column));
    }
 else     if (columnType == Types.DECIMAL) {
      result.put(columnLabel,resultSet.getDouble(column));
    }
 else     if (columnType == Types.BOOLEAN) {
      result.put(columnLabel,resultSet.getBoolean(column));
    }
 else     if (columnType == Types.VARCHAR) {
      result.put(columnLabel,resultSet.getString(column));
    }
 else     if (columnType == Types.LONGVARCHAR) {
      result.put(columnLabel,resultSet.getString(column));
    }
 else     if (columnType == Types.DATE) {
      result.put(columnLabel,resultSet.getDate(column));
    }
 else {
      System.out.println("unknown type (" + columnType + ") for column ?"+ columnLabel+ "?.");
    }
  }
  return result;
}
 

Example 59

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

Source file: AbstractJDBCUtil.java

  21 
vote

protected ArrayList<ArrayList<String>> parseResultSetIntoArrayListOfRows(ResultSet r) throws SQLException {
  ArrayList<ArrayList<String>> vals=new ArrayList<ArrayList<String>>();
  ResultSetMetaData meta=r.getMetaData();
  ArrayList<String> columnNamesRow=new ArrayList<String>();
  for (int i=1; i <= meta.getColumnCount(); i++) {
    columnNamesRow.add(meta.getColumnName(i));
  }
  vals.add(columnNamesRow);
  while (r.next()) {
    ArrayList<String> row=new ArrayList<String>();
    for (int i=1; i <= meta.getColumnCount(); i++) {
      String val=r.getString(i);
      row.add(val);
    }
    vals.add(row);
  }
  return vals;
}
 

Example 60

From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/aladdin/util/.

Source file: ResultSetUtil.java

  19 
vote

public static int toFlag(ResultSetMetaData metaData,int column) throws SQLException {
  int flags=0;
  if (metaData.isNullable(column) == 1) {
    flags|=0001;
  }
  if (metaData.isSigned(column)) {
    flags|=0020;
  }
  if (metaData.isAutoIncrement(column)) {
    flags|=0200;
  }
  return flags;
}
 

Example 61

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

Source file: PreparedStatementHandle.java

  19 
vote

/** 
 * {@inheritDoc}
 * @see java.sql.PreparedStatement#getMetaData()
 */
public ResultSetMetaData getMetaData() throws SQLException {
  checkClosed();
  try {
    return this.internalPreparedStatement.getMetaData();
  }
 catch (  SQLException e) {
    throw this.connectionHandle.markPossiblyBroken(e);
  }
}
 

Example 62

From project jboss-jsf-api_spec, under directory /src/main/java/javax/faces/model/.

Source file: ResultSetDataModel.java

  19 
vote

/** 
 * <p>Return the <code>ResultSetMetaData</code> for the <code>ResultSet</code> we are wrapping, caching it the first time it is returned.</p>
 * @throws FacesException if the <code>ResultSetMetaData</code>cannot be acquired
 */
private ResultSetMetaData getMetaData(){
  if (metadata == null) {
    try {
      metadata=resultSet.getMetaData();
    }
 catch (    SQLException e) {
      throw new FacesException(e);
    }
  }
  return (metadata);
}
 

Example 63

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

Source file: ColumnInfo.java

  19 
vote

void setNull(int nullable){
  if (ResultSetMetaData.columnNullable == nullable) {
    m_bNullable=true;
  }
 else   if (ResultSetMetaData.columnNoNulls == nullable) {
    m_bNotNullable=true;
  }
 else   if (ResultSetMetaData.columnNullableUnknown == nullable) {
    m_bNullableUnknown=true;
  }
}