JavaDeploy JavaDeploy


JDBC - Part 3  «Prev  Next»
  1. How to does on execute an update?

    Answer:
    Creates a Statement object and calls the Statement.executeUpdate method.
    String updateString = "INSERT INTO aDatabase VALUES (some text)";
    int count = stmt.executeUpdate(updateString);
    

  2. How do you update a ResultSet?

    Answer:
    You can update a value in a result set by calling the ResultSet.update < type > method on the row where the cursor is positioned.
    The <type> value here is the same used when retrieving a value from the result set.
    For example,
    1. updateString updates a String value and
    2. updateDouble updates a double value in the result set.
    rs.first();
    updateDouble("balance", rs.getDouble("balance") - 5.00);
    
    The update applies only to the result set until the call to rs.updateRow(), which updates the underlying database.
    To delete the current row, use rs.deleteRow().
    To insert a new row, use rs.moveToInsertRow().

  3. How does one use a PreparedStatement?

    Answer:
    This special type of statement is derived from the more general class, Statement.
    If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead. The advantage of this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled.
    As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first.
    PreparedStatement updateSales = 
    con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
    

  4. How does one call a Stored Procedure from JDBC?

    Answer:
    The first step is to create a CallableStatement object.
    This is done with an open Connection object for both the Statement and PreparedStatement objects.
    A CallableStatement object contains a call to a stored procedure.
    E.g.
    CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
    ResultSet rs = cs.executeQuery();
    

  5. How does one retrieve Warnings?

    Answer:
    SQLWarning objects are a subclass of SQLException that deal with database access warnings.
    Warnings do not stop the execution of an application the way exceptions do.
    Warnings simply alert the user that something did not happen as planned.
    A warning can be reported on
    1. a Connection object,
    2. a Statement object (including PreparedStatement and CallableStatement objects), or
    3. a ResultSet object.

    Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object
    SQLWarning warning = stmt.getWarnings();
    if (warning != null) {
    
    while (warning != null) {
    System.out.println("Message: " + warning.getMessage());
    System.out.println("SQLState: " + warning.getSQLState());
    System.out.print("Vendor error code: ");
    System.out.println(warning.getErrorCode());
    warning = warning.getNextWarning();
    }
    }
    

  6. How is a ResultSet updated?

    Answer:
    Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.
    Connection con = DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, 
    ResultSet.CONCUR_UPDATABLE);
    ResultSet uprs = ("SELECT COF_NAME, PRICE FROM COFFEES");
    

  7. How does one set a scroll type?

    Answer:
    Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter.
    The scroll type value can be one of the following values:
    1. ResultSet.TYPE_FORWARD_ONLY
      Default behavior in JDBC 1.0, application can only call next() on the result set.
    2. ResultSet.SCROLL_SENSITIVE
      ResultSet is fully navigable and updates are reflected in the result set as they occur.
    3. ResultSet.SCROLL_INSENSITIVE
      Result set is fully navigable, but updates are only visible after the result set is closed.
      You need to create a new result set to see the results.

  8. How does one set the update type parameter?

    Answer:
    In the constructors of Statements and PreparedStatements, you may use
    1. ResultSet.CONCUR_READ_ONLY
      The result set is read only.
    2. ResultSet.CONCUR_UPDATABLE
      The result set can be updated.

    You may verify that your database supports these types by calling
    con.getMetaData().supportsResultSetConcurrency(ResultSet.SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);

  9. How do you set up a batch job?

    Answer:
    By default, every JDBC statement is sent to the database individually.
    To send multiple statements at one time ,
    1. use the addBatch() method to append statements to the original statement and
    2. call executeBatch() method to submit entire statement.
    Statement stmt = con.createStatement();
    stmt.addBatch("update registration set balance=balance-5.00 
    where theuser="+theuser);
    stmt.addBatch("insert into auctionitems(description, startprice) 
    values("+description+","+startprice+")");
    ...
    int[] results = stmt.executeBatch();
    

    The return result of the addBatch() method is an array of row counts affected for each statement executed in the batch job.
    If a problem occurred, a java.sql.BatchUpdateException is thrown.
    An incomplete array of row counts can be obtained from BatchUpdateException by calling its getUpdateCounts() method.

  10. How do you store and retrieve an image using JDBC?

    Answer:
    The following block of code can be used to store an image:
    int itemnumber=400456;
    
    File file = new File(itemnumber+".jpg");
    FileInputStream fis = new FileInputStream(file);
    PreparedStatement pstmt = con.prepareStatement
    ("update auctionitems set theimage=? where id= ?");
    pstmt.setBinaryStream(1, fis, (int)file.length()):
    pstmt.setInt(2, itemnumber);
    pstmt.executeUpdate();
    pstmt.close();
    fis.close();
    

    To retrieve an image:
    int itemnumber=400456;
    byte[] imageBytes;//hold an image bytes to pass to createImage().
    
    PreparedStatement pstmt = 
    con.prepareStatement("select theimage from auctionitems where id= ?");
    pstmt.setInt(1, itemnumber);
    ResultSet rs=pstmt.executeQuery();
    if(rs.next()) {
    imageBytes = rs.getBytes(1);
    }
    pstmt.close();
    rs.close();
    
    Image auctionimage = Toolkit.getDefaultToolkit().createImage(imageBytes);