Ejemplo n.º 1
1
  private void AlterarCliente() {
    ResultSet rsCliente =
        FMaster.con.executeSQL(
            "select * from dlcliente where id_cliente  = '" + TFcodCli.getText() + "'");
    try {
      rsCliente.first();
      if (rsCliente.isFirst()) {
        int iresp =
            JOptionPane.showOptionDialog(
                null,
                "Deseja alterar?",
                "",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE,
                null, // do not use a custom Icon
                options, // the titles of buttons
                options[0]); // default button title
        if (iresp == 0) {

          rsCliente.absolute(rsCliente.getRow());
          rsCliente.updateString("nome", TFNome.getText());
          rsCliente.updateString("rua", TFRua.getText());
          rsCliente.updateString("cidade", TFCidade.getText());
          rsCliente.updateString("uf", CBEstado.getSelectedItem().toString());
          rsCliente.updateInt(
              "numero", Integer.parseInt(TFNumero.getText().isEmpty() ? "0" : TFNumero.getText()));
          rsCliente.updateString("bairro", TFBairro.getText());
          rsCliente.updateString("cep", TFCep1.getText().replace(".", "").replace("-", ""));
          rsCliente.updateString("cpf", TFCPF.getText().replace(".", "").replace("-", ""));
          rsCliente.updateString("obs", TAObs.getText());
          rsCliente.updateFloat(
              "taxa_entrega",
              Float.parseFloat(
                  TFVlrTaxaEntrega.getText().isEmpty()
                      ? "0"
                      : TFVlrTaxaEntrega.getText().replace(",", ".")));
          rsCliente.updateInt(
              "id_regiao",
              Integer.parseInt(
                  CBRegiao.getSelectedItem()
                      .toString()
                      .substring(
                          CBRegiao.getSelectedItem().toString().length() - 1,
                          CBRegiao.getSelectedItem().toString().length())));
          rsCliente.updateRow();
          prencherHeder(rsCliente.getInt("id_cliente"));
          PreencherJtableConsulta();
        }
      }
      rsCliente.close();
    } catch (SQLException ex) {
      Logger.getLogger(IFProduto.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  private void testUpdateResetRead() throws SQLException {
    Connection conn = getConnection();
    Statement stat =
        conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
    stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
    stat.execute("INSERT INTO TEST VALUES(2, 'World')");
    ResultSet rs = stat.executeQuery("SELECT * FROM TEST ORDER BY ID");
    rs.next();
    rs.updateInt(1, 10);
    rs.updateRow();
    rs.next();

    rs.updateString(2, "Welt");
    rs.cancelRowUpdates();
    rs.updateString(2, "Welt");

    rs.updateRow();
    rs.beforeFirst();
    rs.next();
    assertEquals(10, rs.getInt(1));
    assertEquals("Hello", rs.getString(2));
    rs.next();
    assertEquals(2, rs.getInt(1));
    assertEquals("Welt", rs.getString(2));

    assertFalse(rs.isClosed());
    rs.close();
    assertTrue(rs.isClosed());

    conn.close();
  }
Ejemplo n.º 3
0
 private void testUpdatePrimaryKey() throws SQLException {
   stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
   stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
   stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
   ResultSet rs = stat.executeQuery("SELECT * FROM TEST");
   rs.next();
   rs.updateInt(1, 2);
   rs.updateRow();
   rs.updateInt(1, 3);
   rs.updateRow();
   stat.execute("DROP TABLE TEST");
 }
  private void testUpdateLob() throws SQLException {
    Connection conn = getConnection();
    Statement stat = conn.createStatement();
    stat.execute(
        "CREATE TABLE object_index " + "(id integer primary key, object other, number integer)");

    PreparedStatement prep =
        conn.prepareStatement("INSERT INTO object_index (id,object)  VALUES (1,?)");
    prep.setObject(1, "hello", Types.JAVA_OBJECT);
    prep.execute();

    ResultSet rs = stat.executeQuery("SELECT object,id,number FROM object_index WHERE id =1");
    rs.next();
    assertEquals("hello", rs.getObject(1).toString());
    stat = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    rs = stat.executeQuery("SELECT object,id,number FROM object_index WHERE id =1");
    rs.next();
    assertEquals("hello", rs.getObject(1).toString());
    rs.updateInt(2, 1);
    rs.updateRow();
    rs.close();
    stat = conn.createStatement();
    rs = stat.executeQuery("SELECT object,id,number FROM object_index WHERE id =1");
    rs.next();
    assertEquals("hello", rs.getObject(1).toString());
    conn.close();
  }
Ejemplo n.º 5
0
  public static void deleteProject(int id) {
    try {
      java.sql.Connection con = Database.getConnection();
      java.sql.Statement s =
          con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

      ResultSet projects;
      projects = s.executeQuery("select * from projects");
      projects.absolute(id);
      projects.deleteRow();

      int size = aantalID("projects");
      projects = s.executeQuery("select * from projects");
      if (projects.next()) {
        while (id < size) {
          projects.absolute(id);
          projects.updateInt("id", id);
          projects.updateRow();
          id++;
          projects.next();
        }
      }
    } catch (SQLException ex) {
      Logger.getLogger(DataLayer.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
  /**
   * Helper function intended to be overwritten by subclasses. Thsi is where the real requiest for
   * IDs happens
   */
  protected void performIDRequest() throws Exception {
    Connection dbConnection = null;

    try {
      try {
        dbConnection = dataSource.getConnection();
        Statement stmt =
            dbConnection.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        ResultSet set = null;
        set =
            stmt.executeQuery(
                "SELECT id, " + dbColumn + " FROM " + dbTable); // $NON-NLS-1$ //$NON-NLS-2$
        if (!set.next()) {
          set.moveToInsertRow();
          set.insertRow();
          set.updateLong(dbColumn, NUM_IDS_GRABBED);
          set.moveToCurrentRow();
          set.next();
        }
        long nextID = set.getLong(dbColumn);
        long upTo = nextID + mCacheQuantity;
        set.updateLong(dbColumn, upTo);
        set.updateRow();
        stmt.close();
        setMaxAllowedID(upTo);
        setNextID(nextID);
      } finally {
        if (dbConnection != null) {
          dbConnection.close();
        }
      }
    } catch (SQLException e) {
      throw new NoMoreIDsException(e);
    }
  }
Ejemplo n.º 7
0
 public void mettreAjourQuantite(String nomArticle, int value) {
   Connection con = null;
   Statement st = null;
   ResultSet rs = null;
   try {
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     con = DriverManager.getConnection("jdbc:mysql://192.168.2.5/inventaire", "guest", "guest");
     st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
     rs = st.executeQuery("SELECT id, nom, quantite FROM articles");
     // modifier la quantité pour l'article nomArticle
     while (rs.next()) {
       int id = rs.getInt(1);
       String nom = rs.getString(2);
       int quantite = rs.getInt(3);
       if (nom.equals(nomArticle)) {
         if ((quantite == 0) && (value == -1)) {
           break;
         }
         rs.updateInt(3, (quantite + value));
         rs.updateRow();
         break;
       }
     }
   } catch (Exception e) {
     System.err.println("Exception: " + e.getMessage());
   } finally {
     try {
       if (rs != null) rs.close();
       if (st != null) st.close();
       if (con != null) con.close();
     } catch (SQLException e) {
     }
   }
 }
Ejemplo n.º 8
0
  public void updateDb(Connection con) {
    try (Statement statement = con.createStatement();
        ResultSet resultSet =
            statement.executeQuery("SELECT * FROM contact where firstname = \"Michael\"")) {
      resultSet.absolute(1); // 1 zmienic na dokładny wiersz w ktorym jest michael - metadata?
      resultSet.updateString("phoneNumber", "+009392032302");
      resultSet.updateRow();
      System.out.println(" After the update");
      System.out.println("ID \tfName \tsurname \temail \t\tphoneNo");
      resultSet.beforeFirst();
      while (resultSet.next()) {
        System.out.println(
            resultSet.getInt("id")
                + "\t"
                + resultSet.getString("name")
                + "t\""
                + resultSet.getString("surname")
                + "t\""
                + resultSet.getString("email")
                + "t\""
                + resultSet.getString("phoneNumber"));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 9
0
  public static void main(String args[]) {

    Connection con;
    Statement stmt;
    ResultSet rs;

    try {
      con = ConnectionUtil.getConnection(args[0]);
      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      rs = stmt.executeQuery("SELECT * FROM Users where name='ian';");

      // Get the resultset ready, update the passwd field, commit
      if (rs.next()) {
        rs.updateString("password", "unguessable");
        rs.updateRow();
      } else {
        System.out.println("Error: user not found");
      }

      rs.close();
      stmt.close();
      con.close();
    } catch (SQLException ex) {
      System.err.println("SQLException: " + ex.getMessage());
    }
  }
Ejemplo n.º 10
0
  public static void deleteThought(int index) {
    try {
      java.sql.Connection con = Database.getConnection();
      java.sql.Statement s =
          con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      int indext = index + 1;
      ResultSet thoughts;
      thoughts = s.executeQuery("select * from thoughts");
      thoughts.absolute(indext);
      thoughts.deleteRow();

      int size = aantalID("thoughts");
      ResultSet thoughts2;
      thoughts2 = s.executeQuery("select * from thoughts");
      if (thoughts2.next()) {
        while (indext < size) {
          thoughts2.absolute(indext);
          thoughts2.updateInt("id", indext);
          thoughts2.updateRow();
          indext++;
          thoughts2.next();
        }
      }

    } catch (SQLException ex) {
      Logger.getLogger(DataLayer.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 11
0
 @Override
 public void updateRow() throws JdbcException {
   try {
     rSet.updateRow();
   } catch (SQLException ex) {
     throw newJdbcException(ex);
   }
 }
 @Override
 public void updateRow() throws SQLException {
   try {
     _res.updateRow();
   } catch (SQLException e) {
     handleException(e);
   }
 }
Ejemplo n.º 13
0
 private Boolean commit() {
   try {
     results.updateRow();
     return true;
   } catch (Exception ex) {
     throw new InvalidQueryException("Database update failed");
   }
 }
  public void testQuery() {

    try {
      Connection c = newConnection();
      Statement st =
          c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
      String s = "CREATE TABLE T (I INTEGER, C CHARACTER(10), B BIT(4) DEFAULT B'')";

      st.execute(s);

      s = "INSERT INTO T VALUES(?,?, DEFAULT)";

      PreparedStatement ps = c.prepareStatement(s);

      for (int i = 1; i <= 20; i++) {
        ps.setInt(1, i);
        ps.setString(2, "TEST " + i);
        ps.execute();
      }

      c.setAutoCommit(false);

      s = "SELECT * FROM T";

      ResultSet rs = st.executeQuery(s);

      rs.absolute(10);
      rs.updateString(2, "UPDATE10");
      rs.updateRow();

      rs.absolute(11);
      rs.deleteRow();

      rs.moveToInsertRow();

      rs.updateInt(1, 1011);
      rs.updateString(2, "INSERT1011");
      rs.updateString(3, "0101");

      rs.insertRow();

      rs.close();

      rs = st.executeQuery(s);

      while (rs.next()) {
        System.out.println(
            "" + rs.getInt(1) + "      " + rs.getString(2) + "      " + rs.getString(3));
      }

    } catch (Exception e) {
      System.out.print(e);
    }
  }
Ejemplo n.º 15
0
  public void saveUserStats(
      String username,
      double x,
      double y,
      int level,
      int experience,
      int gold,
      int hp,
      int maxhp,
      int mp,
      int maxmp,
      int strength,
      int intellect,
      int agility,
      int dexterity,
      int vitality,
      int luck,
      String image,
      int region)
      throws DatabaseException, SQLException {
    Transaction trans = new JDBCTransaction(createConnection());
    Connection connection = ((JDBCTransaction) trans).getConnection();
    Statement stmt =
        connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
    String query = "SELECT * FROM users WHERE username like '" + username + "'";
    ResultSet result = stmt.executeQuery(query); // executeQuery(query);

    if (result.next()) {
      result.updateDouble("x", x);
      result.updateDouble("y", y);
      //  	result.updateString("race", race);
      //  	result.updateString("class", Class);
      //  	result.updateString("privs", privs);
      //  	result.updateString("status", status);
      result.updateInt("level", level);
      result.updateInt("experience", experience);
      result.updateInt("gold", gold);
      result.updateInt("hp", hp);
      result.updateInt("maxhp", maxhp);
      result.updateInt("mp", mp);
      result.updateInt("maxmp", maxmp);
      result.updateInt("strength", strength);
      result.updateInt("intellect", intellect);
      result.updateInt("agility", agility);
      result.updateInt("dexterity", dexterity);
      result.updateInt("vitality", vitality);
      result.updateInt("luck", luck);
      result.updateString("image", image);
      result.updateInt("region", region);
      result.updateRow();
    }
  }
Ejemplo n.º 16
0
  public static void changeProject(int id, String change) {
    try {
      java.sql.Connection con = Database.getConnection();
      java.sql.Statement s =
          con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

      ResultSet thought;
      thought = s.executeQuery("select * from projects");
      thought.absolute(id);
      thought.updateString("name", change);
      thought.updateRow();
    } catch (SQLException ex) {
      Logger.getLogger(DataLayer.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 17
0
  /**
   * Tests calling updateLong on all columns of the row.
   *
   * @exception SQLException database access error. Causes test to fail with an error.
   */
  public void testUpdateLong() throws SQLException {
    Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery(SELECT_STMT);
    rs.next();

    for (int i = 1; i <= COLUMNS; i++) {
      rs.updateLong(i, 2L);
      assertEquals("Expected rs.getLong(" + i + ") to match updated value", 2L, rs.getLong(i));
    }
    rs.updateRow();
    rs.close();
    checkColumnsAreUpdated();

    s.close();
  }
Ejemplo n.º 18
0
  // DESDE AQUI AGREGADO POR GHUCHET
  private void completarMovimiento(MMovement move) {
    // Preparar el movimiento
    move.setDocAction(X_M_Movement.DOCACTION_Prepare);
    DocumentEngine.processIt(move, X_M_Movement.DOCACTION_Prepare);
    move.save();
    commit();
    move.load(get_TrxName());
    if (move.getDocStatus().equals("IN")) {
      ADialog.error(EnvConstants.WINDOW_INFO, new Container(), "NoLines");
    } else {

      // Aca debo actualizar las cantidades aprobadas
      String sql =
          "SELECT QtyRequired, XX_ApprovedQty FROM M_MOVEMENTLINE WHERE M_MOVEMENT_ID = "
              + move.getM_Movement_ID();
      PreparedStatement ps_1 =
          DB.prepareStatement(
              sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, null);
      ResultSet rs_1 = null;
      // System.out.println(sql);
      int qty_required = 0;
      try {
        rs_1 = ps_1.executeQuery();
        while (rs_1.next()) {
          qty_required = rs_1.getInt("QtyRequired");
          rs_1.updateInt("XX_ApprovedQty", qty_required);
          rs_1.updateRow();
        }
      } catch (Exception e) {
        e.printStackTrace();

      } finally {
        try {
          rs_1.close();
          ps_1.close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }

      move.setXX_Status("PE");
      move.setXX_RequestDate(move.getUpdated());
      move.save();

      // Se envian correos dependiendo del tipo de documento
      enviarCorreoATienda(move, Env.getCtx().getContextAsInt("#XX_L_MT_PTRANSFERAPPROVAL_ID"));
    }
  }
Ejemplo n.º 19
0
  /**
   * Tests calling setNull on all columns
   *
   * @exception SQLException database access error. Causes test to fail with an error.
   */
  public void testUpdateNull() throws SQLException {
    Statement s = createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
    ResultSet rs = s.executeQuery(SELECT_STMT);
    rs.next();

    for (int i = 1; i <= COLUMNS; i++) {
      rs.updateNull(i);
      assertNull("Expected rs.getObject(" + i + ") to be null", rs.getObject(i));
      assertTrue("Expected rs.wasNull() to return true", rs.wasNull());
    }
    rs.updateRow();
    rs.close();
    checkColumnsAreNull();

    s.close();
  }
Ejemplo n.º 20
0
  public static void ProcessCustomerPayment(Connection conn) {
    // This function updates is_paid so billing staff can keep track of the payments customers have
    // made

    int c_id = BooksAThousand.getIntFromShell("Enter customer ID: ");

    try {
      Statement statement =
          conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      ResultSet rs =
          statement.executeQuery(
              "select customer_id, isbn, quantity, price, customer_order_date, is_paid"
                  + " from customer_order where customer_id="
                  + c_id
                  + " and is_paid='N'");
      if (rs.next()) {
        System.out.println("Outstanding payments:");
        System.out.printf(
            "Order  %-10s %-5s %-5s %-10s %-10s\n", "ISBN", "Quant", "Price", "Total", "Date");
        Date date;
        int i = 0;
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy hh:mm");
        do {
          i++;
          date = rs.getDate(5);
          System.out.printf(
              "%-5s: %-10s %-5d %-5d %-10d %-10s \n",
              i,
              rs.getInt(2),
              rs.getInt(3),
              rs.getInt(4),
              rs.getInt(3) * rs.getInt(4),
              sdf.format(date));
        } while (rs.next());
        int order = BooksAThousand.getIntFromShell("Which order to mark as paid: ");
        rs.absolute(i);
        rs.updateString(6, "Y");
        rs.updateRow();
        System.out.println("Update successful.");

      } else {
        System.out.println("This user has no unpaid orders");
      }
    } catch (Throwable e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 21
0
  @Override
  public boolean update(Teacher obj) {
    try {
      Statement stat = conn.createStatement();
      ResultSet rs = stat.executeQuery("SELECT * FROM teachers WHERE tid = " + obj.getId());
      rs.first();
      rs.updateString("tname", obj.getName());
      rs.updateRow();
      rs.close();
      stat.close();
      return true;

    } catch (SQLException e) {
      e.printStackTrace();
      return false;
    }
  }
 /**
  * Test optimistic updates throw exception if row is changed on disk.
  *
  * <p>When running on SQL Server this test will exercise MSCursorResultSet. When running on Sybase
  * this test will exercise CachedResultSet.
  */
 public void testOptimisticUpdates() throws Exception {
   Connection con2 = getConnection();
   try {
     dropTable("jTDS_CachedCursorTest");
     Statement stmt =
         con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
     ResultSet rs;
     stmt.execute("CREATE TABLE jTDS_CachedCursorTest (id int primary key, data varchar(255))");
     for (int i = 0; i < 4; i++) {
       stmt.executeUpdate(
           "INSERT INTO jTDS_CachedCursorTest VALUES(" + i + ", 'Table A line " + i + "')");
     }
     // Open cursor
     rs = stmt.executeQuery("SELECT id, data FROM jTDS_CachedCursorTest");
     Statement stmt2 = con2.createStatement();
     while (rs.next()) {
       if (rs.getInt(1) == 1) {
         assertEquals(
             1,
             stmt2.executeUpdate(
                 "UPDATE jTDS_CachedCursorTest SET data = 'NEW VALUE' WHERE id = 1"));
         rs.updateString(2, "TEST UPDATE");
         try {
           rs.updateRow();
           assertNotNull(rs.getWarnings());
           assertEquals(
               "Expected optimistic update exception", "24000", rs.getWarnings().getSQLState());
         } catch (SQLException e) {
           // Expected exception as row has been modified on disk
           assertEquals("24000", e.getSQLState());
         }
       }
     }
     rs.close();
     stmt.close();
   } finally {
     if (con2 != null) {
       con2.close();
     }
     dropTable("jTDS_CachedCursorTest");
   }
 }
 /**
  * Test updateable result set where table is not keyed. Uses a server side cursor and positioned
  * updates on Sybase.
  */
 public void testUpdateNoKeys() throws Exception {
   Statement stmt = con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
   stmt.execute("CREATE TABLE ##TESTNOKEY (id int, data varchar(255))");
   for (int i = 0; i < 4; i++) {
     stmt.executeUpdate("INSERT INTO ##TESTNOKEY VALUES(" + i + ", 'Test line " + i + "')");
   }
   ResultSet rs = stmt.executeQuery("SELECT * FROM ##TESTNOKEY");
   assertTrue(rs.next());
   assertTrue(rs.next());
   rs.updateString(2, "UPDATED");
   rs.updateRow();
   rs.close();
   rs = stmt.executeQuery("SELECT * FROM ##TESTNOKEY");
   while (rs.next()) {
     if (rs.getInt(1) == 1) {
       assertEquals("UPDATED", rs.getString(2));
     }
   }
   stmt.close();
 }
Ejemplo n.º 24
0
  private void AlteraCliente() {
    ResultSet rsCliComanda =
        FMaster.con.executeSQL(
            "select * from atncomcli where id_comanda = '"
                + comanda
                + "' and id_com_clie = '"
                + id_com_clie
                + "'");
    try {
      rsCliComanda.first();
      if (rsCliComanda.isFirst()) {
        rsCliComanda.updateString("nome", TFNomecliente.getText());
        rsCliComanda.updateRow();
        dispose();
      }

    } catch (SQLException ex) {
      Logger.getLogger(DLCadCliComanda.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
Ejemplo n.º 25
0
  public void modifyPrices(float percentage) throws SQLException {
    Statement stmt = null;
    try {
      stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
      ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

      while (uprs.next()) {
        float f = uprs.getFloat("PRICE");
        uprs.updateFloat("PRICE", f * percentage);
        uprs.updateRow();
      }

    } catch (SQLException e) {
      JDBCTutorialUtilities.printSQLException(e);
    } finally {
      if (stmt != null) {
        stmt.close();
      }
    }
  }
  public static void main(String[] args) {
    try {
      try (Connection conn = getConnection()) {
        String sql = "select id, name from student";
        // TYPE_SCROLL_SENSITIVE == 结果集可以滚动且对数据库变化不敏感;
        // CONCUR_UPDATABLE == 且结果集能够应用于更新数据库;
        Statement stat =
            conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
        // get 可更新的 结果集
        ResultSet rs = stat.executeQuery(sql);

        int rowno;
        while (true) {
          rowno = rs.getRow();
          if (rowno < 1) {
            rs.absolute(1); // 将游标设置到指定的行号上
          }

          if (rs.getRow() % 2 != 0) {
            rs.updateString("name", rs.getString("name") + "_odd");
          } else {
            rs.updateString("name", rs.getString("name") + "_even");
          }
          rs.updateRow();
          // attention for rs.getString not changing row cursor
          System.out.println("row[" + rs.getRow() + "] = " + rs.getString(2));

          // 将游标向后或向前移动多行: rs.relative(n); n为正数, 向前移动;或负数, 向后移动; n为0, 不移动;
          rs.relative(1);
          if (rs.isAfterLast()) {
            break;
          }
        }

        stat.close();
        conn.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Ejemplo n.º 27
0
  protected boolean modifyProcess(Object object) {
    ArrayList array = this.manager.entity2Array(this, object, EntityManager.OPERATION.MODIFY);

    try {
      this.rs =
          conex.updateField(((String) array.get(0)), String.valueOf(array.get(array.size() - 1)));
      rs.next();

      do {
        int size = array.size() - 1;
        for (int i = 1; i < size; i++) {
          Object[] obj = (Object[]) array.get(i);

          String column = (String) obj[0];
          Object value = obj[1];

          rs.updateObject(column, value);
          rs.updateRow();
        }
      } while (rs.next());

      int index =
          Integer.parseInt(
              String.valueOf(array.get(array.size() - 1))
                  .substring(String.valueOf(array.get(array.size() - 1)).indexOf("=") + 1));

      if (this.collection) {
        this.saveMany2Many(((String) array.get(0)), false, index);
      }
      this.manager.updateCache(object.getClass(), this);
    } catch (Exception e) {
      try {
        conex.cancelTransaction();
      } catch (Exception ex) {
        return false;
      }
      return false;
    }

    return true;
  }
Ejemplo n.º 28
0
  /**
   * Adds item to the order and decreases client's account balance.
   *
   * @param db Database connection object.
   * @param itemId Item id to add.
   * @throws SQLException when something goes wrong.
   */
  protected static void addOrder(final Connection db, final int itemId) throws SQLException {
    try (PreparedStatement itemStatement = db.prepareStatement(ADD_ITEM)) {
      itemStatement.setInt(1, 1);
      itemStatement.setInt(2, 1);
      itemStatement.setInt(DatabaseSetup.CLIENT_ID, itemId);

      itemStatement.execute();
    }

    try (PreparedStatement accountStatement =
        db.prepareStatement(
            GET_ACCOUNT, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE)) {
      accountStatement.setInt(1, 1);
      try (ResultSet rs = accountStatement.executeQuery()) {
        rs.next();
        int value = rs.getInt("ACCOUNT");
        value -= ORDER_PRICE;
        rs.updateInt("ACCOUNT", value);
        rs.updateRow();
      }
    }
  }
  void updateid(String phn_no, String p_id) {
    try {
      String host = "jdbc:derby://localhost:1527/JhalMuri";
      String uName = "jhalmuri";
      String uPass = "******";
      try (Connection con = DriverManager.getConnection(host, uName, uPass)) {
        Statement stmt =
            con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        String sql = "SELECT * FROM POSTID WHERE PHN='" + phn_no + "'";
        try (ResultSet rs = stmt.executeQuery(sql)) {
          rs.first();
          rs.updateString("ID", p_id);
          rs.updateRow();
          rs.close();
        }
        con.close();
      }
    } catch (SQLException err) {
      System.out.println(err.getMessage());
    }
  }
Ejemplo n.º 30
0
 private void testOwnUpdates() throws SQLException {
   DatabaseMetaData meta = conn.getMetaData();
   for (int i = 0; i < 3; i++) {
     int type =
         i == 0
             ? ResultSet.TYPE_FORWARD_ONLY
             : i == 1 ? ResultSet.TYPE_SCROLL_INSENSITIVE : ResultSet.TYPE_SCROLL_SENSITIVE;
     assertTrue(meta.ownUpdatesAreVisible(type));
     assertFalse(meta.ownDeletesAreVisible(type));
     assertFalse(meta.ownInsertsAreVisible(type));
   }
   stat = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
   stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR(255))");
   stat.execute("INSERT INTO TEST VALUES(1, 'Hello')");
   stat.execute("INSERT INTO TEST VALUES(2, 'World')");
   ResultSet rs;
   rs = stat.executeQuery("SELECT ID, NAME FROM TEST ORDER BY ID");
   rs.next();
   rs.next();
   rs.updateString(2, "Hallo");
   rs.updateRow();
   assertEquals("Hallo", rs.getString(2));
   stat.execute("DROP TABLE TEST");
 }