コード例 #1
0
ファイル: LongObject.java プロジェクト: exss/replicatoros
  /**
   * puts the value for the column aginst the column Name
   *
   * @param os
   * @param rows
   * @param oldResultSet
   * @param index
   * @param modifiedColumns
   * @param columnName
   * @throws SQLException
   * @throws IOException
   */
  public void writeUpdate(
      Writer os,
      ResultSet rows,
      ResultSet oldResultSet,
      int index,
      HashMap modifiedColumns,
      String columnName,
      ArrayList encodedCols)
      throws SQLException, IOException {
    Object newObject = rows.getObject(index);
    Object oldObject = oldResultSet.getObject(index);

    if (newObject == null) {
      write(os, "NULL", encodedCols, columnName);
      if (oldObject != null) {
        modifiedColumns.put(columnName, "NULL");
      }
    } else {
      write(os, newObject, encodedCols, columnName);
      if (oldObject != null) {
        if (!(newObject.equals(oldObject))) {
          modifiedColumns.put(columnName, newObject);
        }
      } else {
        modifiedColumns.put(columnName, newObject);
      }
    }
  }
コード例 #2
0
  /** private method which actually will do all of our work for the sample */
  private void executeSample() {

    String query = "select anEmployee from staff2";
    try {
      Statement stmt = _con.createStatement();
      ;

      // Execute the query which will return an Employee object
      // We will cast this using the Person interface. Note the
      // Person interface class MUST be in your CLASSPATH. You
      // Do not need Employee in your CLASSPATH.
      ResultSet rs = stmt.executeQuery(query);

      output("***Using interface class\n");
      while (rs.next()) {
        Person aPerson = (Person) rs.getObject(1);
        displayMethods(aPerson.getClass());
        output(
            "The person is: "
                + aPerson.toString()
                + "\nFirst Name= "
                + aPerson.getFirstName()
                + "\nLast Name= "
                + aPerson.getLastName()
                + "\n");
      }
      // Now execute the same query, but this time we will use
      // reflection to access the class.  Again, only the interface
      // Person is required in the CLASSPATH
      rs = stmt.executeQuery(query);

      output("***Using reflection\n");
      Object theObj = null;
      while (rs.next()) {
        theObj = rs.getObject(1);
        output("The person is: " + theObj.toString() + "\n");
        Class theClass = theObj.getClass();
        displayMethods(theClass);
        Method m1 = theClass.getMethod("toString", new Class[0]);
        Method m2 = theClass.getMethod("getFirstName", new Class[0]);
        Method m3 = theClass.getMethod("getLastName", new Class[0]);
        output(
            "The person is: "
                + (Object) m1.invoke(theObj, new Object[0])
                + "\nFirst Name= "
                + (Object) m2.invoke(theObj, new Object[0])
                + "\nLast Name= "
                + (Object) m3.invoke(theObj, new Object[0])
                + "\n");
      }
      rs.close();
      stmt.close();
    } catch (SQLException sqe) {
      displaySQLEx(sqe);
    } catch (Exception e) {
      error("Unexpected exception : " + e.toString() + "\n");
      e.printStackTrace();
    }
  }
コード例 #3
0
 private double fetchValueOfDouble(String fieldname) {
   // As with fetch...String, the point is to handle nulls gracefully.
   try {
     return (rs_instrument.getObject(fieldname) == null)
         ? 0
         : Double.parseDouble(rs_instrument.getObject(HEIGHT).toString());
   } catch (SQLException sqle) {
     System.out.println("Unable to fetch value of " + fieldname + ".\n" + sqle);
     return -1;
   }
 }
コード例 #4
0
 // some data processing
 private String fetchValueOfString(String fieldname) {
   // This method reads in a value and translates nulls into an empty string so the constructor
   // doesn't choke.
   try {
     return (rs_instrument.getObject(fieldname) == null)
         ? ""
         : rs_instrument.getObject(fieldname).toString();
   } catch (SQLException sqle) {
     System.out.println("Unable to fetch value of " + fieldname + ".\n" + sqle);
     return "?????";
   }
 }
コード例 #5
0
ファイル: GridRowSet.java プロジェクト: aforino/h2gis
  @Override
  public void reset() throws SQLException {
    cellI = 0;
    cellJ = 0;
    firstRow = false;
    // We compute the extend according the first input value
    if (isTable) {
      Statement statement = connection.createStatement();
      ResultSet rs =
          statement.executeQuery(
              "select ST_Extent("
                  + getFirstGeometryField(tableName, connection)
                  + ")  from "
                  + tableName);
      try {
        rs.next();
        Geometry geomExtend = (Geometry) rs.getObject(1);
        if (geomExtend == null) {
          throw new SQLException("The envelope cannot be null.");
        } else {
          envelope = geomExtend.getEnvelopeInternal();
          initParameters();
        }

      } finally {
        rs.close();
      }
    } else {
      if (envelope == null) {
        throw new SQLException("The input geometry used to compute the grid cannot be null.");
      } else {
        initParameters();
      }
    }
  }
コード例 #6
0
  // execute and get results
  private void execute(Connection conn, String text, Writer writer, boolean commaSeparator)
      throws SQLException {

    BufferedWriter buffer = new BufferedWriter(writer);
    Statement stmt = conn.createStatement();
    stmt.execute(text);
    ResultSet rs = stmt.getResultSet();
    ResultSetMetaData metadata = rs.getMetaData();
    int nbCols = metadata.getColumnCount();
    String[] labels = new String[nbCols];
    int[] colwidths = new int[nbCols];
    int[] colpos = new int[nbCols];
    int linewidth = 1;

    // read each occurrence
    try {
      while (rs.next()) {
        for (int i = 0; i < nbCols; i++) {
          Object value = rs.getObject(i + 1);
          if (value != null) {
            buffer.write(value.toString());
            if (commaSeparator) buffer.write(",");
          }
        }
      }
      buffer.flush();
      rs.close();
    } catch (IOException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
      // ok, exit from the loop
    } catch (SQLException ex) {
      if (Debug.isDebug()) ex.printStackTrace();
    }
  }
コード例 #7
0
  private void jTbdescripcionKeyPressed(
      java.awt.event.KeyEvent evt) { // GEN-FIRST:event_jTbdescripcionKeyPressed

    try {
      // se comienza la conexion con la base de datos
      try {
        con = new Conexion();

      } catch (ClassNotFoundException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (SQLException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (InstantiationException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalAccessException ex) {
        Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
      }

      String nom = jTbdescripcion.getText();
      String sql = "SELECT * FROM productos WHERE nombre_producto LIKE '" + nom + "%'";
      rs = con.Consulta(sql);

      if (rs == null)
        JOptionPane.showMessageDialog(
            null, "No se encontro: " + jTbdescripcion.getText() + " en la base de datos.");

      // Para establecer el modelo al JTable

      DefaultTableModel buscar =
          new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int rowIndex, int vColIndex) {
              return false;
            }
          };
      this.jTbuscar.setModel(buscar);

      // Obteniendo la informacion de las columnas que estan siendo consultadas
      ResultSetMetaData rsMd = rs.getMetaData();
      // La cantidad de columnas que tiene la consulta
      int cantidadColumnas = rsMd.getColumnCount();
      // Establecer como cabezeras el nombre de las colimnas
      for (int i = 1; i <= cantidadColumnas; i++) {
        buscar.addColumn(rsMd.getColumnLabel(i));
      }

      while (rs.next()) {
        Object[] fila = new Object[cantidadColumnas];

        for (int i = 0; i < cantidadColumnas; i++) {

          fila[i] = rs.getObject(i + 1);
        }
        buscar.addRow(fila);
      }

    } catch (SQLException ex) {
      Logger.getLogger(Interface.class.getName()).log(Level.SEVERE, null, ex);
    }
  } // GEN-LAST:event_jTbdescripcionKeyPressed
コード例 #8
0
ファイル: SQLExecutorImpl.java プロジェクト: mabe02/jdbw
  @Override
  public void batchWrite(BatchUpdateHandler handler, List<String> batchedSQL) throws SQLException {
    Statement statement = null;
    try {
      statement = connection.createStatement();
      for (String row : batchedSQL) {
        addBatch(statement, row);
      }

      int[] batchResult = executeBatch(statement);
      handler.onBatchResult(Arrays.copyOf(batchResult, batchResult.length));

      ResultSet generatedKeys = getGeneratedKeys(statement);
      if (generatedKeys != null) {
        while (generatedKeys.next()) {
          handler.onGeneratedKey(generatedKeys.getObject(1));
        }
        generatedKeys.close();
      }

      SQLWarning warning = getWarnings(statement);
      if (warning != null) {
        handler.onWarning(warning);
      }
    } finally {
      if (statement != null) {
        try {
          close(statement);
        } catch (SQLException e) {
          LOGGER.error("Unable to close statement after batch write", e);
        }
      }
    }
  }
コード例 #9
0
 private Double toDouble(ResultSet rs, String column) throws SQLException {
   Object obj = rs.getObject(column);
   if (obj instanceof Double) {
     return (Double) obj;
   }
   return null;
 }
コード例 #10
0
ファイル: database.java プロジェクト: GroupI9/IBMS
 public Object get_field(String field_name) {
   try {
     return results.getObject(field_name);
   } catch (Exception ex) {
     throw new InvalidQueryException("Database access failed");
   }
 }
コード例 #11
0
  /** Creates new form PrincipalCliente */
  public ModificarAdmin() {
    initComponents();
    conexioninicio ci = new conexioninicio();
    ci.conectar();
    this.setSize(470, 650);
    this.setLocationRelativeTo(null); // Centra la ventana Splash
    try {
      Connection con = DriverManager.getConnection(ci.getURl(), ci.getLogin(), ci.getPassword());
      //  System.out.println("Conexion a la base de datos cliente realizada con exito! ");
      Statement stmt = con.createStatement();

      ResultSet rs = stmt.executeQuery("SELECT * FROM tienda.estado ;");
      // obteniendo la informacion de las columnas que estan siendo consultadas
      ResultSetMetaData rsMd = rs.getMetaData();
      // La cantidad de columnas que tiene la consulta
      int cantidadColumnas = rsMd.getColumnCount();
      // Establecer como cabezeras el nombre de las columnas

      // Creando las filas para el Jtable
      while (rs.next()) {
        Object[] fila = new Object[cantidadColumnas];
        for (int i = 1; i < cantidadColumnas; i++) {
          jComboBox1.addItem(rs.getObject(i + 1));
        }
      }
      rs.close();
      con.close();

    } catch (Exception e) {

      JOptionPane.showMessageDialog(null, e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
    }
  }
コード例 #12
0
ファイル: TestUtil.java プロジェクト: fabiogm/PhoenixTesting
 /**
  * Asserts that we find the expected values in the result set. We don't know the order, since we
  * don't always have an order by and we're going through indexes, but we assert that each expected
  * result occurs once as expected (in any order).
  */
 public static void assertValuesEqualsResultSet(ResultSet rs, List<List<Object>> expectedResults)
     throws SQLException {
   int expectedCount = expectedResults.size();
   int count = 0;
   List<List<Object>> actualResults = Lists.newArrayList();
   List<Object> errorResult = null;
   while (rs.next() && errorResult == null) {
     List<Object> result = Lists.newArrayList();
     for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
       result.add(rs.getObject(i + 1));
     }
     if (!expectedResults.contains(result)) {
       errorResult = result;
     }
     actualResults.add(result);
     count++;
   }
   assertTrue(
       "Could not find "
           + errorResult
           + " in expected results: "
           + expectedResults
           + " with actual results: "
           + actualResults,
       errorResult == null);
   assertEquals(expectedCount, count);
 }
コード例 #13
0
  public static void populateTable() {
    System.out.println("started");
    Connection conn = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e1) {
      // TODO Auto-generated catch block
      e1.printStackTrace();
    }
    try {

      conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "");
      stmt = conn.prepareStatement("select * from class");

      rs = stmt.executeQuery();
      ResultSetMetaData metaData = rs.getMetaData();
      System.out.println("connected");

      Vector<String> columnNames = new Vector<String>(); // vector to store names of columns

      int columnCount = metaData.getColumnCount(); // get number of columns

      for (int i = 1; i <= columnCount; i++) {
        System.out.println("loop columnams.add");

        columnNames.add(metaData.getColumnName(i)); // adding column names in the vector
      }

      Vector<Vector<Object>> data = new Vector<Vector<Object>>();
      while (rs.next()) {
        System.out.println("while rs.next");

        Vector<Object> vector = new Vector<Object>();
        for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
          vector.add(rs.getObject(columnIndex));
        }
        data.add(vector);
      }
      System.out.println("done loop");

      DefaultTableModel temp = new DefaultTableModel(data, columnNames);

      //  JTable tablez = new JTable(temp);
      // System.out.println(tablez);

      table.setModel(temp);
      table.setModel(temp);

      // table = tablez;
      // System.out.println();

    } catch (SQLException e1) {

      e1.printStackTrace();
    }
  }
コード例 #14
0
ファイル: project3.java プロジェクト: emadonop/ergasia3
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    Statement stmt;
    ResultSet rs;
    Connection con = null;

    try {
      Class.forName("com.mysql.jdbc.Driver");
      String connectionUrl = "jdbc:mysql://localhost/myflickr?" + "user=root&password=123456";
      con = DriverManager.getConnection(connectionUrl);

      if (con != null) {
        System.out.println("connected to mysql");
      }
    } catch (SQLException e) {
      System.out.println("SQL Exception: " + e.toString());
    } catch (ClassNotFoundException cE) {
      System.out.println("Class Not Found Exception: " + cE.toString());
    }

    try {
      stmt = con.createStatement();

      System.out.println("SELECT * FROM flickrusers WHERE name='" + username + "'");
      rs = stmt.executeQuery("SELECT * FROM flickrusers WHERE name='" + username + "'");

      while (rs.next()) {

        if (rs.getObject(1).toString().equals(username)) {

          out.println("<h1>To username pou epileksate uparxei hdh</h1>");
          out.println("<a href=\"project3.html\">parakalw dokimaste kapoio allo.</a>");

          stmt.close();
          rs.close();
          return;
        }
      }
      stmt.close();
      rs.close();

      stmt = con.createStatement();

      if (!stmt.execute("INSERT INTO flickrusers VALUES('" + username + "', '" + password + "')")) {
        out.println("<h1>Your registration is completed  " + username + "</h1>");
        out.println("<a href=\"index.jsp\">go to the login menu</a>");
        registerListener.Register(username);
      } else {
        out.println("<h1>To username pou epileksate uparxei hdh</h1>");
        out.println("<a href=\"project3.html\">Register</a>");
      }
    } catch (SQLException e) {
      throw new ServletException("Servlet Could not display records.", e);
    }
  }
コード例 #15
0
  /*
   * Execute query against a list of sensors
   *
   * */
  public static String executeQuery(
      String envelope, String query, String matchingSensors, String format) throws ParseException {

    // String matchingSensors = getListOfSensorsAsString(envelope);

    String reformattedQuery = reformatQuery(query, matchingSensors);
    StringBuilder sb = new StringBuilder();
    Connection connection = null;

    try {
      connection = Main.getDefaultStorage().getConnection();
      Statement statement =
          connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
      ResultSet results = statement.executeQuery(reformattedQuery);
      ResultSetMetaData metaData; // Additional information about the results
      int numCols, numRows; // How many rows and columns in the table
      metaData = results.getMetaData(); // Get metadata on them
      numCols = metaData.getColumnCount(); // How many columns?
      results.last(); // Move to last row
      numRows = results.getRow(); // How many rows?

      String s;

      // System.out.println("* Executing query *\n" + reformattedQuery + "\n***");

      // headers
      // sb.append("# Query: " + query + NEWLINE);
      sb.append("# Query: " + reformattedQuery.replaceAll("\n", "\n# ") + NEWLINE);

      sb.append("# ");
      // System.out.println("ncols: " + numCols);
      // System.out.println("nrows: " + numRows);
      for (int col = 0; col < numCols; col++) {
        sb.append(metaData.getColumnLabel(col + 1));
        if (col < numCols - 1) sb.append(SEPARATOR);
      }
      sb.append(NEWLINE);

      for (int row = 0; row < numRows; row++) {
        results.absolute(row + 1); // Go to the specified row
        for (int col = 0; col < numCols; col++) {
          Object o = results.getObject(col + 1); // Get value of the column
          // logger.warn(row + " , "+col+" : "+ o.toString());
          if (o == null) s = "null";
          else s = o.toString();
          if (col < numCols - 1) sb.append(s).append(SEPARATOR);
          else sb.append(s);
        }
        sb.append(NEWLINE);
      }
    } catch (SQLException e) {
      sb.append("ERROR in execution of query: " + e.getMessage());
    } finally {
      Main.getDefaultStorage().close(connection);
    }

    return sb.toString();
  }
コード例 #16
0
ファイル: DBQueriesTest.java プロジェクト: kminder/cqengine
  public static <K, V> Map<K, V> resultSetToMap(final ResultSet resultSet) {

    try {
      final Map<K, V> map = new LinkedHashMap<K, V>();

      while (resultSet.next()) {

        K key = (K) resultSet.getObject(1);
        V value = (V) resultSet.getObject(2);

        map.put(key, value);
      }

      return map;
    } catch (Exception e) {
      throw new IllegalStateException("Unable to transform the resultSet into a Map", e);
    }
  }
コード例 #17
0
  public void calcular(Conectar cn, String fechaInicio, String fechaFin)
      throws SQLException, IOException, ParseException {

    // Cuenta el número de dispositivos que han pasado por cada nodo, osea cuántas veces un
    // dispositivo ha pasado por un nodo determinado.
    Statement st1 = cn.crearSt();
    String query =
        "select paso.idNodo, nodo.nombre, idDispositivo, count(idDispositivo), YEAR(FROM_UNIXTIME(tInicio/1000)) as year, "
            + "MONTH(FROM_UNIXTIME(tInicio/1000)) as month, DAYOFMONTH(FROM_UNIXTIME(tInicio/1000)) as day, "
            + "HOUR(FROM_UNIXTIME(tInicio/1000)) as hour, DAYNAME(FROM_UNIXTIME(tInicio/1000)) as nameDay, FROM_UNIXTIME(tInicio/1000) as fecha from paso, nodo where paso.idNodo=nodo.idNodo "
            + "and FROM_UNIXTIME(tInicio/1000) < '"
            + fechaFin
            + "' and FROM_UNIXTIME(tInicio/1000) > '"
            + fechaInicio
            + "' group by nodo.IdNodo, idDispositivo, year, month, day, hour;";
    System.err.println(query);
    ResultSet rs = st1.executeQuery(query);

    String s;
    // DateFormat format = new SimpleDateFormat("MMddyyHHmmss");
    while (rs.next()) {
      s =
          rs.getObject(1)
              + "\t"
              + rs.getObject(2)
              + "\t"
              + rs.getObject(3)
              + "\t"
              + rs.getObject(4)
              + "\t"
              + rs.getObject(5)
              + "\t"
              + rs.getObject(6)
              + "\t"
              + rs.getObject(7)
              + "\t"
              + rs.getObject(8)
              + "\t"
              + rs.getObject(9)
              + "\n";
      bw.write(s);
      System.err.print(s);
      // sumaTiempo=sumaTiempo+Long.parseLong(rs.getObject(2).toString())-Long.parseLong(rs.getObject(1).toString());

    }

    rs.close();
    bw.close();
  }
コード例 #18
0
ファイル: JdbcDataSource.java プロジェクト: rmuir/lucene-solr
    protected Map<String, Object> getARow(
        ResultSet resultSet,
        boolean convertType,
        List<String> colNames,
        Map<String, Integer> fieldNameVsType) {
      if (resultSet == null) return null;
      Map<String, Object> result = new HashMap<>();
      for (String colName : colNames) {
        try {
          if (!convertType) {
            // Use underlying database's type information except for BigDecimal and BigInteger
            // which cannot be serialized by JavaBin/XML. See SOLR-6165
            Object value = resultSet.getObject(colName);
            if (value instanceof BigDecimal || value instanceof BigInteger) {
              result.put(colName, value.toString());
            } else {
              result.put(colName, value);
            }
            continue;
          }

          Integer type = fieldNameVsType.get(colName);
          if (type == null) type = Types.VARCHAR;
          switch (type) {
            case Types.INTEGER:
              result.put(colName, resultSet.getInt(colName));
              break;
            case Types.FLOAT:
              result.put(colName, resultSet.getFloat(colName));
              break;
            case Types.BIGINT:
              result.put(colName, resultSet.getLong(colName));
              break;
            case Types.DOUBLE:
              result.put(colName, resultSet.getDouble(colName));
              break;
            case Types.DATE:
              result.put(colName, resultSet.getTimestamp(colName));
              break;
            case Types.BOOLEAN:
              result.put(colName, resultSet.getBoolean(colName));
              break;
            case Types.BLOB:
              result.put(colName, resultSet.getBytes(colName));
              break;
            default:
              result.put(colName, resultSet.getString(colName));
              break;
          }
        } catch (SQLException e) {
          logError("Error reading data ", e);
          wrapAndThrow(SEVERE, e, "Error reading data from database");
        }
      }
      return result;
    }
コード例 #19
0
ファイル: StatementExecution.java プロジェクト: MMatten/dbfit
 public Object getReturnValue() throws SQLException {
   if (functionReturnValueViaResultSet) {
     rs.next();
     Object o = rs.getObject(1);
     rs.close();
     return o;
   } else {
     return getObject(returnValueInd);
   }
 }
コード例 #20
0
 private void checkBooleanValue(ResultSet rs, boolean expectedValue, Boolean expectedNull)
     throws SQLException {
   rs.next();
   for (int i = 1; i <= 14; i++) {
     assertEquals(expectedValue, rs.getBoolean(i));
     if (i == 1 || i == 2) {
       assertEquals(expectedNull, rs.getObject(i));
     }
   }
 }
コード例 #21
0
  /** @return {@code true} If next row was fetched successfully. */
  private boolean fetchNext() {
    if (data == null) return false;

    try {
      if (!data.next()) return false;

      for (int c = 0; c < row.length; c++) row[c] = data.getObject(c + 1);

      return true;
    } catch (SQLException e) {
      throw new IgniteException(e);
    }
  }
コード例 #22
0
  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); // In SQL the first column is indexed with 1 not 0
        System.out.print(o.toString() + " ");
      }
      System.out.println(" ");
    }
  }
コード例 #23
0
  public int applyParamsToInsertAndUpdateStatement(
      PreparedStatement pstmt, TemporalEntity sde, Date transactionTime, Date createdTime)
      throws Exception {
    int idx = applyParamsToInsertStatement(pstmt, sde, transactionTime, createdTime);

    currentRS.last();

    for (String notUpdateName : notUpdatedColumns) {
      Object o = currentRS.getObject(notUpdateName);
      pstmt.setObject(idx++, o);
    }

    return idx;
  }
コード例 #24
0
ファイル: SqlStatement.java プロジェクト: sohu001/mondrian
 public Object get(ResultSet resultSet, int column) throws SQLException {
   switch (this) {
     case OBJECT:
       return resultSet.getObject(column + 1);
     case STRING:
       return resultSet.getString(column + 1);
     case INT:
       return resultSet.getInt(column + 1);
     case LONG:
       return resultSet.getLong(column + 1);
     case DOUBLE:
       return resultSet.getDouble(column + 1);
     default:
       throw Util.unexpected(this);
   }
 }
コード例 #25
0
ファイル: StatementExecution.java プロジェクト: MMatten/dbfit
 public Object getGeneratedKey(Class<?> type) throws SQLException, IllegalAccessException {
   ResultSet rs = statement.getGeneratedKeys();
   if (rs.next()) { // todo: first try to find by name (mysql does not support name-based return
     // keys)
     Object value;
     if (type == Integer.class) {
       value = rs.getInt(1);
     } else if (type == Long.class) {
       value = rs.getLong(1);
     } else {
       value = rs.getObject(1);
     }
     return value;
   }
   throw new IllegalAccessException("statement has not generated any keys");
 }
コード例 #26
0
ファイル: PrepStmtTest.java プロジェクト: gwenn/sqlitejdbc
  @Ignore
  @Test
  public void getObject() throws SQLException {
    stat.executeUpdate(
        "create table testobj (" + "c1 integer, c2 float, c3, c4 varchar, c5 bit, c6, c7);");
    PreparedStatement prep = conn.prepareStatement("insert into testobj values (?,?,?,?,?,?,?);");

    prep.setInt(1, Integer.MAX_VALUE);
    prep.setFloat(2, Float.MAX_VALUE);
    prep.setDouble(3, Double.MAX_VALUE);
    prep.setLong(4, Long.MAX_VALUE);
    prep.setBoolean(5, false);
    prep.setByte(6, (byte) 7);
    prep.setBytes(7, b1);
    prep.executeUpdate();

    ResultSet rs = stat.executeQuery("select c1,c2,c3,c4,c5,c6,c7 from testobj;");
    assertTrue(rs.next());

    assertEquals(Integer.MAX_VALUE, rs.getInt(1));
    assertEquals(Integer.MAX_VALUE, (int) rs.getLong(1));
    assertEquals(Float.MAX_VALUE, rs.getFloat(2));
    assertEquals(Double.MAX_VALUE, rs.getDouble(3));
    assertEquals(Long.MAX_VALUE, rs.getLong(4));
    assertFalse(rs.getBoolean(5));
    assertEquals((byte) 7, rs.getByte(6));
    assertArrayEq(rs.getBytes(7), b1);

    assertNotNull(rs.getObject(1));
    assertNotNull(rs.getObject(2));
    assertNotNull(rs.getObject(3));
    assertNotNull(rs.getObject(4));
    assertNotNull(rs.getObject(5));
    assertNotNull(rs.getObject(6));
    assertNotNull(rs.getObject(7));
    assertTrue(rs.getObject(1) instanceof Integer);
    assertTrue(rs.getObject(2) instanceof Double);
    assertTrue(rs.getObject(3) instanceof Double);
    assertTrue(rs.getObject(4) instanceof String);
    assertTrue(rs.getObject(5) instanceof Integer);
    assertTrue(rs.getObject(6) instanceof Integer);
    assertTrue(rs.getObject(7) instanceof byte[]);
    rs.close();
  }
コード例 #27
0
 /** getObject. */
 public void test() throws Exception {
   PreparedStatement statement = connection.prepareStatement(sql);
   ResultSet result = statement.executeQuery();
   int size = result.getMetaData().getColumnCount();
   Vector rows = new Vector();
   while (result.next()) {
     Vector row = new Vector(size);
     for (int column = 1; column <= size; column++) {
       Object value = result.getObject(column);
       value = ConversionManager.getDefaultManager().convertObject(value, ClassConstants.SQLDATE);
       row.add(value);
     }
     rows.add(row);
   }
   result.close();
   statement.close();
 }
コード例 #28
0
ファイル: Query.java プロジェクト: CraxGrix/myJDBCFramework
 @Override
 public List<Map<String, Object>> queryByParamsForMapList() throws SQLException {
   preStat = getPreparedStatement();
   rs = preStat.executeQuery();
   mapList.clear();
   Map<String, Object> map = null;
   ResultSetMetaData rsm = rs.getMetaData();
   int cnt = rsm.getColumnCount();
   while (rs.next()) {
     map = new HashMap<String, Object>(cnt);
     for (int i = 0; i < cnt; i++) {
       map.put(rsm.getColumnName(i), rs.getObject(i));
     }
     mapList.add(map);
   }
   return mapList;
 }
コード例 #29
0
ファイル: DBUtils.java プロジェクト: GayashanNA/carbon-data
 /**
  * Processes a particular SQL Array object and interprets its value as a ParamValue object.
  *
  * @param sqlArray SQL Array element.
  * @param paramValue Parameter value object initialized to contain an array of ParamValues.
  * @return ParamValue object representing the SQL Array.
  * @throws SQLException Throws an SQL Exception if the result set is not accessible.
  */
 public static ParamValue processSQLArray(Array sqlArray, ParamValue paramValue)
     throws SQLException {
   ResultSet rs = sqlArray.getResultSet();
   while (rs.next()) {
     Object arrayEl = rs.getObject(2);
     if (arrayEl instanceof Struct) {
       paramValue.getArrayValue().add(new ParamValue((Struct) arrayEl));
     } else if (arrayEl instanceof Array) {
       paramValue
           .getArrayValue()
           .add(processSQLArray((Array) arrayEl, new ParamValue(ParamValue.PARAM_VALUE_ARRAY)));
     } else {
       paramValue.getArrayValue().add(new ParamValue(String.valueOf(arrayEl)));
     }
   }
   rs.close();
   return paramValue;
 }
コード例 #30
0
ファイル: Query.java プロジェクト: kptran/sql2o
  public <T> List<T> executeAndFetch(Class returnType) {
    List list = new ArrayList();
    PojoMetadata metadata =
        new PojoMetadata(returnType, this.isCaseSensitive(), this.getColumnMappings());
    try {
      // java.util.Date st = new java.util.Date();
      long start = System.currentTimeMillis();
      ResultSet rs = statement.executeQuery();
      long afterExecQuery = System.currentTimeMillis();

      ResultSetMetaData meta = rs.getMetaData();

      while (rs.next()) {

        Pojo pojo = new Pojo(metadata, this.isCaseSensitive());

        // Object obj = returnType.newInstance();
        for (int colIdx = 1; colIdx <= meta.getColumnCount(); colIdx++) {
          String colName = meta.getColumnName(colIdx);
          pojo.setProperty(colName, rs.getObject(colIdx));
        }

        list.add(pojo.getObject());
      }

      rs.close();
      long afterClose = System.currentTimeMillis();

      logger.info(
          "total: {} ms, execution: {} ms, reading and parsing: {} ms; executed [{}]",
          new Object[] {
            afterClose - start,
            afterExecQuery - start,
            afterClose - afterExecQuery,
            this.getName() == null ? "No name" : this.getName()
          });
    } catch (SQLException ex) {
      throw new Sql2oException("Database error", ex);
    } finally {
      closeConnectionIfNecessary();
    }

    return list;
  }