package org.plenix.translator.sql;

import java.sql.*;
import java.util.Vector;
import java.util.Hashtable;
import DBConnectionManager;

public class DBUtil {
  public static Vector executeQuery(String connectionName, String queryStatement)
    throws SQLException
  {
    Connection connection = null;
    Statement statement = null;

    DBConnectionManager connectionManager = DBConnectionManager.getInstance();

    try {
      connection = connectionManager.getConnection(connectionName);

      if (connection == null) {
        throw new SQLException("Can't get database connection '" + connectionName + "'");
      }

      statement = connection.createStatement();

      ResultSet resultSet = statement.executeQuery(queryStatement);
      ResultSetMetaData metaData = resultSet.getMetaData();

      int columnCount = metaData.getColumnCount();
      String[] columnNames = new String[columnCount];

      for (int i = 0; i < columnCount; i++) {
        columnNames[i] = metaData.getColumnName(i + 1).toUpperCase();
      }

      Vector rowSet = new Vector();

      while (resultSet.next()) {
        Hashtable row = new Hashtable();

        for (int i = 0; i < columnCount; i++) {
          Object columnValue = resultSet.getObject(i + 1);

	  if (columnValue instanceof String) {
	    columnValue = new String(resultSet.getBytes(i + 1));
	  }

          if (!resultSet.wasNull()) {
            row.put(columnNames[i], columnValue);
          }
        }

        rowSet.addElement(row);
      }

      return rowSet;
    } catch (Exception e) {
      // e.printStackTrace(); 
      return null;
    } finally {
      try {
        if (statement != null) {
          statement.close();
        }

        if (connection != null) {
          connectionManager.freeConnection(connectionName, connection);
        }
      } catch (Exception x) { }
    }
  }
}