Example usage for java.sql ResultSet beforeFirst

List of usage examples for java.sql ResultSet beforeFirst

Introduction

In this page you can find the example usage for java.sql ResultSet beforeFirst.

Prototype

void beforeFirst() throws SQLException;

Source Link

Document

Moves the cursor to the front of this ResultSet object, just before the first row.

Usage

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;//from  ww  w .  ja v a 2s .  c  om
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        String query = "select id, name from employees";
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
        rs.first();
        rs.deleteRow();
        rs.beforeFirst();
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/testdb", "root", "");

    Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);

    String query = "SELECT id, code, name, quantity, price FROM products";
    ResultSet uprs = statement.executeQuery(query);

    while (uprs.next()) {
        System.out.println(uprs.getString("id") + ":" + uprs.getString("code") + ":" + uprs.getString("name")
                + ":" + uprs.getInt("quantity") + ":" + uprs.getDouble("price"));
    }/* w  w w  .  j a v  a  2 s . c o  m*/
    uprs.first();
    uprs.updateString("name", "Java");
    uprs.updateRow();
    uprs.next();
    uprs.deleteRow();

    uprs.moveToInsertRow();
    uprs.updateString("code", "1");
    uprs.updateString("name", "Data Structures");
    uprs.updateInt("quantity", 1);
    uprs.updateDouble("price", 5.99);
    uprs.insertRow();

    uprs.beforeFirst();
    while (uprs.next()) {
        System.out.println(uprs.getString("id") + "\t" + uprs.getString("code") + "\t" + uprs.getString("name")
                + "\t" + uprs.getInt("quantity") + "\t" + uprs.getDouble("price"));
    }
    connection.close();
}

From source file:InsertRows.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*  w w  w .  java 2  s .  co  m*/
    Statement stmt;
    try {
        Class.forName("myDriver.ClassName");

    } catch (java.lang.ClassNotFoundException e) {
        System.err.print("ClassNotFoundException: ");
        System.err.println(e.getMessage());
    }

    try {

        con = DriverManager.getConnection(url, "myLogin", "myPassword");

        stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);

        ResultSet uprs = stmt.executeQuery("SELECT * FROM COFFEES");

        uprs.moveToInsertRow();

        uprs.updateString("COF_NAME", "Kona");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 10.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.updateString("COF_NAME", "Kona_Decaf");
        uprs.updateInt("SUP_ID", 150);
        uprs.updateFloat("PRICE", 11.99f);
        uprs.updateInt("SALES", 0);
        uprs.updateInt("TOTAL", 0);

        uprs.insertRow();

        uprs.beforeFirst();

        System.out.println("Table COFFEES after insertion:");
        while (uprs.next()) {
            String name = uprs.getString("COF_NAME");
            int id = uprs.getInt("SUP_ID");
            float price = uprs.getFloat("PRICE");
            int sales = uprs.getInt("SALES");
            int total = uprs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        uprs.close();
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,null)");
    st.executeUpdate("insert into survey (id,name ) values (3,'Tom')");
    ResultSet rs = st.executeQuery("SELECT * FROM survey");

    // Move cursor forward
    while (rs.next()) {
        // Get data at cursor
        String id = rs.getString(1);
        String name = rs.getString(2);
    }//from   ww  w  .  jav  a2s .c o  m

    // Move cursor backward
    while (rs.previous()) {
        // Get data at cursor
        String id = rs.getString(1);
        String name = rs.getString(2);
    }

    // Move cursor to the first row
    rs.first();

    // Move cursor to the last row
    rs.last();

    // Move cursor to the end, after the last row
    rs.afterLast();

    // Move cursor to the beginning, before the first row.
    // cursor position is 0.
    rs.beforeFirst();

    // Move cursor to the second row
    rs.absolute(2);

    // Move cursor to the last row
    rs.absolute(-1);

    // Move cursor to the second-to-last row
    rs.absolute(-2);

    // Move cursor down 5 rows from the current row. If this moves
    // cursor beyond the last row, cursor is put after the last row
    rs.relative(5);

    // Move cursor up 3 rows from the current row. If this moves
    // cursor beyond the first row, cursor is put before the first row
    rs.relative(-3);

    rs.close();
    st.close();
    conn.close();

}

From source file:InsertRowUpdatableResultSet_MySQL.java

public static void main(String[] args) {
    Connection conn = null;//from ww  w .  ja  v a  2  s . c  o m
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        String query = "select id, name from employees";
        stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
        // Move cursor to the "insert row"
        rs.moveToInsertRow();
        // Set values for the new row.
        rs.updateString("id", "001");
        rs.updateString("name", "newName");
        // Insert the new row
        rs.insertRow();
        // scroll from the top again
        rs.beforeFirst();
        while (rs.next()) {
            String id = rs.getString(1);
            String name = rs.getString(2);
            System.out.println("id=" + id + "  name=" + name);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    } finally {
        // release database resources
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:UpdateableRs.java

public static void printRs(ResultSet rs) throws SQLException {
    rs.beforeFirst();

    while (rs.next()) {
        int ssn = rs.getInt("ssn");
        String name = rs.getString("name");
        double salary = rs.getDouble("salary");

        System.out.print("Row Number=" + rs.getRow());
        System.out.print(", SSN: " + ssn);
        System.out.print(", Name: " + name);
        System.out.println(", Salary: $" + salary);
    }// w  w w.  j  a  va2 s .  c  o  m
    System.out.println();
}

From source file:org.biblionum.ouvrage.modele.CategorieOuvrageModele.java

/**
 * Java method that updates a row in the generated sql table
 *
 * @param con (open java.sql.Connection)
 * @param designation_categorie//from  w w w. java 2s . c o  m
 * @return boolean (true on success)
 * @throws SQLException
 */
public static boolean updateCategorieouvrage(DataSource ds, int keyId, String designation_categorie)
        throws SQLException {
    con = ds.getConnection();
    String sql = "SELECT * FROM categorieouvrage WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (designation_categorie != null) {
        entry.updateString("designation_categorie", designation_categorie);
    }

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5a.java

public static String writeTable(ResultSet results, ResultSetMetaData resultsMetaData)
        throws IOException, SQLException {
    int numColumns = resultsMetaData.getColumnCount();
    results.beforeFirst();
    StringBuffer t = new StringBuffer();
    t.append("<p>");

    if (results.next()) {
        for (int i = 1; i < (numColumns + 1); i++) {
            t.append(resultsMetaData.getColumnName(i));
            t.append(", ");
        }/*from w  w  w.  j a v a  2  s  . c  om*/

        t.append("<br />");
        results.beforeFirst();

        while (results.next()) {

            for (int i = 1; i < (numColumns + 1); i++) {
                t.append(results.getString(i));
                t.append(", ");
            }

            t.append("<br />");
        }

    } else {
        t.append("Query Successful; however no data was returned from this query.");
    }

    t.append("</p>");
    return (t.toString());
}

From source file:org.biblionum.commentaire.modele.CommentaireOuvragesModele.java

public static boolean updateOuvragetype(DataSource ds, int keyId, String contenu_commentaire,
        String date_commentaire, int utilisateurid, int ouvrageid) throws SQLException {

    Connection con = ds.getConnection();
    String sql = "SELECT * FROM ouvragetype WHERE id = ?";
    PreparedStatement statement = con.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_UPDATABLE);
    statement.setInt(1, keyId);/*  w w w  . ja va  2  s.com*/
    ResultSet entry = statement.executeQuery();

    entry.last();
    int rows = entry.getRow();
    entry.beforeFirst();
    if (rows == 0) {
        entry.close();
        statement.close();
        con.close();
        return false;
    }
    entry.next();

    if (contenu_commentaire != null) {
        entry.updateString("contenu_commentaire", contenu_commentaire);
    }
    if (date_commentaire != null) {
        entry.updateString("date_commentaire", date_commentaire);
    }
    entry.updateInt("utilisateurid", utilisateurid);
    entry.updateInt("ouvrageid", ouvrageid);

    entry.updateRow();
    entry.close();
    statement.close();
    con.close();
    return true;
}

From source file:recite18th.library.Db.java

public static Object getBySql(String sql, String fqn) {
    Object modelInstance = null;// w  w  w.  j  a v a 2s  . c  o m
    try {
        Class modelClass = Class.forName(fqn);
        ResultSetMetaData metaData;
        String columnName;
        String fieldValue;
        Field field;

        PreparedStatement pstmt = getCon().prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        Logger.getLogger(Db.class.getName()).log(Level.INFO, sql);
        ResultSet resultSet = pstmt.executeQuery();
        metaData = resultSet.getMetaData();
        int nColoumn = metaData.getColumnCount();
        resultSet.beforeFirst();
        Logger.getLogger(Db.class.getName()).log(Level.INFO, "About to process data");
        if (resultSet.next()) {
            Logger.getLogger(Db.class.getName()).log(Level.INFO, "Data exist");
            modelInstance = modelClass.newInstance();
            for (int i = 1; i <= nColoumn; i++) {
                //the good ol'ways.. don't use BeanUtils... The problem is, how can it able to get the 
                //field from super class??
                //field = modelInstance.getClass().getDeclaredField(columnName);
                //field.set(modelInstance, fieldValue);
                columnName = metaData.getColumnName(i);
                fieldValue = resultSet.getString(i);
                PropertyUtils.setSimpleProperty(modelInstance, columnName, fieldValue);
            }
        } else {
            Logger.getLogger(Db.class.getName()).log(Level.INFO, "Data !exist");
        }
    } catch (Exception ex) {
        Logger.getLogger(Db.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
    }
    return modelInstance;
}