Example usage for java.sql ResultSet getInt

List of usage examples for java.sql ResultSet getInt

Introduction

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

Prototype

int getInt(String columnLabel) throws SQLException;

Source Link

Document

Retrieves the value of the designated column in the current row of this ResultSet object as an int in the Java programming language.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");

    ResultSet rsColumns = null;
    DatabaseMetaData meta = conn.getMetaData();
    rsColumns = meta.getColumns(null, "%", "code", "%");

    while (rsColumns.next()) {
        String columnType = rsColumns.getString("TYPE_NAME");
        String columnName = rsColumns.getString("COLUMN_NAME");
        int size = rsColumns.getInt("COLUMN_SIZE");
        int nullable = rsColumns.getInt("NULLABLE");
        int position = rsColumns.getInt("ORDINAL_POSITION");

        System.out.println("column name=" + columnName);
        System.out.println("type=" + columnType);
        System.out.println("size=" + size);
        if (nullable == DatabaseMetaData.columnNullable) {
            System.out.println("nullable is true");
        } else {//from ww w. j a  v  a 2s.c om
            System.out.println("nullable is false");
        }
        System.out.println("position" + position);
    }

    conn.close();
}

From source file:BatchUpdate.java

public static void main(String args[]) throws SQLException {

    ResultSet rs = null;/*from   w w w  . ja  va  2 s  . com*/
    PreparedStatement ps = null;

    String url = "jdbc:mySubprotocol:myDataSource";

    Connection con;
    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");
        con.setAutoCommit(false);

        stmt = con.createStatement();

        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut', 49, 9.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Amaretto_decaf', 49, 10.99, 0, 0)");
        stmt.addBatch("INSERT INTO COFFEES " + "VALUES('Hazelnut_decaf', 49, 10.99, 0, 0)");

        int[] updateCounts = stmt.executeBatch();
        con.commit();
        con.setAutoCommit(true);

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

        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 (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Message:  " + b.getMessage());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts:  ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + "   ");
        }
        System.err.println("");

    } catch (SQLException ex) {
        System.err.println("-----SQLException-----");
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:de.tudarmstadt.ukp.csniper.resbuild.EvaluationItemFixer.java

public static void main(String[] args) {
    connect(HOST, DATABASE, USER, PASSWORD);

    Map<Integer, String> items = new HashMap<Integer, String>();
    Map<Integer, String> failed = new HashMap<Integer, String>();

    // fetch coveredTexts of dubious items and clean it
    PreparedStatement select = null;
    try {//  w  w w .  ja  v  a2  s.c  o  m
        StringBuilder selectQuery = new StringBuilder();
        selectQuery.append("SELECT * FROM EvaluationItem ");
        selectQuery.append("WHERE LOCATE(coveredText, '  ') > 0 ");
        selectQuery.append("OR LOCATE('" + LRB + "', coveredText) > 0 ");
        selectQuery.append("OR LOCATE('" + RRB + "', coveredText) > 0 ");
        selectQuery.append("OR LEFT(coveredText, 1) = ' ' ");
        selectQuery.append("OR RIGHT(coveredText, 1) = ' ' ");

        select = connection.prepareStatement(selectQuery.toString());
        log.info("Running query [" + selectQuery.toString() + "].");
        ResultSet rs = select.executeQuery();

        while (rs.next()) {
            int id = rs.getInt("id");
            String coveredText = rs.getString("coveredText");

            try {
                // special handling of double whitespace: in this case, re-fetch the text
                if (coveredText.contains("  ")) {
                    coveredText = retrieveCoveredText(rs.getString("collectionId"), rs.getString("documentId"),
                            rs.getInt("beginOffset"), rs.getInt("endOffset"));
                }

                // replace bracket placeholders and trim the text
                coveredText = StringUtils.replace(coveredText, LRB, "(");
                coveredText = StringUtils.replace(coveredText, RRB, ")");
                coveredText = coveredText.trim();

                items.put(id, coveredText);
            } catch (IllegalArgumentException e) {
                failed.put(id, e.getMessage());
            }
        }
    } catch (SQLException e) {
        log.error("Exception while selecting: " + e.getMessage());
    } finally {
        closeQuietly(select);
    }

    // write logs
    BufferedWriter bwf = null;
    BufferedWriter bws = null;
    try {
        bwf = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(LOG_FAILED)), "UTF-8"));
        for (Entry<Integer, String> e : failed.entrySet()) {
            bwf.write(e.getKey() + " - " + e.getValue() + "\n");
        }

        bws = new BufferedWriter(
                new OutputStreamWriter(new FileOutputStream(new File(LOG_SUCCESSFUL)), "UTF-8"));
        for (Entry<Integer, String> e : items.entrySet()) {
            bws.write(e.getKey() + " - " + e.getValue() + "\n");
        }
    } catch (IOException e) {
        log.error("Got an IOException while writing the log files.");
    } finally {
        IOUtils.closeQuietly(bwf);
        IOUtils.closeQuietly(bws);
    }

    log.info("Texts for [" + items.size() + "] items need to be cleaned up.");

    // update the dubious items with the cleaned coveredText
    PreparedStatement update = null;
    try {
        String updateQuery = "UPDATE EvaluationItem SET coveredText = ? WHERE id = ?";

        update = connection.prepareStatement(updateQuery);
        int i = 0;
        for (Entry<Integer, String> e : items.entrySet()) {
            int id = e.getKey();
            String coveredText = e.getValue();

            // update item in database
            update.setString(1, coveredText);
            update.setInt(2, id);
            update.executeUpdate();
            log.debug("Updating " + id + " with [" + coveredText + "]");

            // show percentage of updated items
            i++;
            int part = (int) Math.ceil((double) items.size() / 100);
            if (i % part == 0) {
                log.info(i / part + "% finished (" + i + "/" + items.size() + ").");
            }
        }
    } catch (SQLException e) {
        log.error("Exception while updating: " + e.getMessage());
    } finally {
        closeQuietly(update);
    }

    closeQuietly(connection);
}

From source file:TypeConcurrency.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/* ww w.  ja  va2s .  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_READ_ONLY);

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

        int type = srs.getType();

        System.out.println("srs is type " + type);

        int concur = srs.getConcurrency();

        System.out.println("srs has concurrency " + concur);
        while (srs.next()) {
            String name = srs.getString("COF_NAME");
            int id = srs.getInt("SUP_ID");
            float price = srs.getFloat("PRICE");
            int sales = srs.getInt("SALES");
            int total = srs.getInt("TOTAL");
            System.out.print(name + "   " + id + "   " + price);
            System.out.println("   " + sales + "   " + total);
        }

        srs.close();
        stmt.close();
        con.close();

    } catch (SQLException ex) {
        System.err.println("-----SQLException-----");
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:jfutbol.com.jfutbol.GcmSender.java

public static void main(String[] args) {
    log.info("GCM - Sender running");
    do {//w  ww.  j  a  va2s . c o m

        Connection conn = null;
        Connection conn2 = null;
        Statement stmt = null;
        Statement stmt2 = null;

        try {
            // STEP 2: Register JDBC driver
            Class.forName(JDBC_DRIVER);
            // STEP 3: Open a connection
            // System.out.println("Connecting to database...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
            conn2 = DriverManager.getConnection(DB_URL, USER, PASS);
            // STEP 4: Execute a query
            // System.out.println("Creating statement...");
            stmt = conn.createStatement();
            String sql;
            sql = "SELECT userId FROM notifications WHERE sentByGCM=0 GROUP BY userId";
            ResultSet rs = stmt.executeQuery(sql);
            // STEP 5: Extract data from result set
            while (rs.next()) {
                log.info("Notification found");
                int userId = rs.getInt("userId");

                stmt2 = conn2.createStatement();
                String sql2;
                sql2 = "SELECT COUNT(id) notificationCounter FROM notifications WHERE status=0 AND userId="
                        + userId;
                ResultSet rs2 = stmt2.executeQuery(sql2);
                int notificationCounter = rs2.getInt("notificationCounter");
                rs2.close();
                stmt2.close();
                // Retrieve by column name

                // Display values
                // System.out.print("userId: " + userId);
                // System.out.print(", notificationCounter: " +
                // notificationCounter);
                SendNotification(userId, notificationCounter);
            }
            // STEP 6: Clean-up environment
            rs.close();
            stmt.close();
            conn.close();
            conn2.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            log.error(se.getMessage());
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            log.error(e.getMessage());
            e.printStackTrace();
        } finally {
            // finally block used to close resources
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException se2) {
                log.error(se2.getMessage());
            } // nothing we can do
            try {
                if (conn != null)
                    conn.close();
            } catch (SQLException se) {
                log.error(se.getMessage());
                se.printStackTrace();
            } // end finally try
        } // end try
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
    } while (1 != 0);
}

From source file:InsertStores.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from  ww w  .  j  a  v a2s.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();
        con.setAutoCommit(false);

        String insertStore1 = "INSERT INTO STORES VALUES (" + "100001, "
                + "ADDRESS(888, 'Main_Street', 'Rancho_Alegre', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore1);

        String insertStore2 = "INSERT INTO STORES VALUES (" + "100002, "
                + "ADDRESS(1560, 'Alder', 'Ochos_Pinos', " + "'CA', '94049'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000001))";

        stmt.addBatch(insertStore2);

        String insertStore3 = "INSERT INTO STORES VALUES (" + "100003, "
                + "ADDRESS(4344, 'First_Street', 'Verona', " + "'CA', '94545'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore3);

        String insertStore4 = "INSERT INTO STORES VALUES (" + "100004, "
                + "ADDRESS(321, 'Sandy_Way', 'La_Playa', " + "'CA', '94544'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf', " + "'Kona', 'Kona_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000002))";

        stmt.addBatch(insertStore4);

        String insertStore5 = "INSERT INTO STORES VALUES (" + "100005, "
                + "ADDRESS(1000, 'Clover_Road', 'Happyville', " + "'CA', '90566'), "
                + "COF_ARRAY('Colombian', 'French_Roast', 'Espresso', "
                + "'Colombian_Decaf', 'French_Roast_Decaf'), "
                + "(SELECT OID FROM MANAGERS WHERE MGR_ID = 000003))";

        stmt.addBatch(insertStore5);

        int[] updateCounts = stmt.executeBatch();

        ResultSet rs = stmt.executeQuery("SELECT * FROM STORES");

        System.out.println("Table STORES after insertion:");
        System.out.println("STORE_NO  LOCATION          COF_TYPE     MGR");
        while (rs.next()) {
            int storeNo = rs.getInt("STORE_NO");
            Struct location = (Struct) rs.getObject("LOCATION");
            Object[] locAttrs = location.getAttributes();
            Array coffeeTypes = rs.getArray("COF_TYPE");
            String[] cofTypes = (String[]) coffeeTypes.getArray();

            Ref managerRef = rs.getRef("MGR");
            PreparedStatement pstmt = con.prepareStatement("SELECT MANAGER FROM MANAGERS WHERE OID = ?");
            pstmt.setRef(1, managerRef);
            ResultSet rs2 = pstmt.executeQuery();
            rs2.next();
            Struct manager = (Struct) rs2.getObject("MANAGER");
            Object[] manAttrs = manager.getAttributes();

            System.out.print(storeNo + "   ");
            System.out.print(locAttrs[0] + " " + locAttrs[1] + " " + locAttrs[2] + ", " + locAttrs[3] + "  "
                    + locAttrs[4] + " ");
            for (int i = 0; i < cofTypes.length; i++)
                System.out.print(cofTypes[i] + " ");
            System.out.println(manAttrs[1] + ", " + manAttrs[2]);

            rs2.close();
            pstmt.close();
        }

        rs.close();
        stmt.close();
        con.close();

    } catch (BatchUpdateException b) {
        System.err.println("-----BatchUpdateException-----");
        System.err.println("SQLState:  " + b.getSQLState());
        System.err.println("Message:  " + b.getMessage());
        System.err.println("Vendor:  " + b.getErrorCode());
        System.err.print("Update counts:  ");
        int[] updateCounts = b.getUpdateCounts();
        for (int i = 0; i < updateCounts.length; i++) {
            System.err.print(updateCounts[i] + "   ");
        }
        System.err.println("");

    } catch (SQLException ex) {
        System.err.println("SQLException: " + ex.getMessage());
        System.err.println("SQLState:  " + ex.getSQLState());
        System.err.println("Message:  " + ex.getMessage());
        System.err.println("Vendor:  " + ex.getErrorCode());
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    ResultSet rsColumns = null;
    DatabaseMetaData meta = conn.getMetaData();
    rsColumns = meta.getColumns(null, null, "survey", null);
    while (rsColumns.next()) {
        String columnName = rsColumns.getString("COLUMN_NAME");
        System.out.println("column name=" + columnName);
        String columnType = rsColumns.getString("TYPE_NAME");
        System.out.println("type:" + columnType);
        int size = rsColumns.getInt("COLUMN_SIZE");
        System.out.println("size:" + size);
        int nullable = rsColumns.getInt("NULLABLE");
        if (nullable == DatabaseMetaData.columnNullable) {
            System.out.println("nullable true");
        } else {//w  w w.  j ava2  s  .  co m
            System.out.println("nullable false");
        }
        int position = rsColumns.getInt("ORDINAL_POSITION");
        System.out.println("position:" + position);

    }

    st.close();
    conn.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getHSQLConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("create table survey (id int,name varchar);");
    st.executeUpdate("create view surveyView as (select * from survey);");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");
    st.executeUpdate("insert into survey (id,name ) values (2,'anotherValue')");

    ResultSet rs = null;
    PreparedStatement ps = null;//from  w  ww . j  a  va  2s .c  o  m

    String query = "select id, name from survey where id = ?";

    ps = conn.prepareStatement(query);
    // specify values for all input parameters
    ps.setInt(1, 001); // set the first parameter: id

    // now, PreparedStatement object is ready to be executed.
    rs = ps.executeQuery();
    // iterate the result set object
    while (rs.next()) {
        int id = rs.getInt(1);
        String name = rs.getString(2);
        System.out.println("[id=" + id + "][name=" + name + "]");
    }

    // NOTE: you may use PreparedStatement as many times as you want
    // here we use it for another set of parameters:
    ps.setInt(1, 002); // set the first parameter: id

    // now, PreparedStatement object is ready to be executed.
    rs = ps.executeQuery();
    // iterate the result set object
    while (rs.next()) {
        int id = rs.getInt(1);
        String name = rs.getString(2);
        System.out.println("[id=" + id + "][name=" + name + "]");
    }
    rs.close();
    ps.close();
    conn.close();

}

From source file:SelectRecordsUsingPreparedStatement.java

public static void main(String[] args) {
    ResultSet rs = null;
    Connection conn = null;//www.  jav  a  2  s  . c  o  m
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        String query = "select deptno, deptname, deptloc from dept where deptno > ?";

        pstmt = conn.prepareStatement(query); // create a statement
        pstmt.setInt(1, 1001); // set input parameter
        rs = pstmt.executeQuery();
        // extract data from the ResultSet
        while (rs.next()) {
            int dbDeptNumber = rs.getInt(1);
            String dbDeptName = rs.getString(2);
            String dbDeptLocation = rs.getString(3);
            System.out.println(dbDeptNumber + "\t" + dbDeptName + "\t" + dbDeptLocation);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            rs.close();
            pstmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getMySqlConnection();
    System.out.println("Got Connection.");
    Statement st = conn.createStatement();
    st.executeUpdate("drop table survey;");
    st.executeUpdate("create table survey (id int,name varchar(30));");
    st.executeUpdate("insert into survey (id,name ) values (1,'nameValue')");

    DatabaseMetaData dbMetaData = conn.getMetaData();
    ResultSet rs = dbMetaData.getProcedureColumns(conn.getCatalog(), null, "procedureNamePattern",
            "columnNamePattern");

    while (rs.next()) {
        // get stored procedure metadata
        String procedureCatalog = rs.getString(1);
        String procedureSchema = rs.getString(2);
        String procedureName = rs.getString(3);
        String columnName = rs.getString(4);
        short columnReturn = rs.getShort(5);
        int columnDataType = rs.getInt(6);
        String columnReturnTypeName = rs.getString(7);
        int columnPrecision = rs.getInt(8);
        int columnByteLength = rs.getInt(9);
        short columnScale = rs.getShort(10);
        short columnRadix = rs.getShort(11);
        short columnNullable = rs.getShort(12);
        String columnRemarks = rs.getString(13);

        System.out.println("stored Procedure name=" + procedureName);
        System.out.println("procedureCatalog=" + procedureCatalog);
        System.out.println("procedureSchema=" + procedureSchema);
        System.out.println("procedureName=" + procedureName);
        System.out.println("columnName=" + columnName);
        System.out.println("columnReturn=" + columnReturn);
        System.out.println("columnDataType=" + columnDataType);
        System.out.println("columnReturnTypeName=" + columnReturnTypeName);
        System.out.println("columnPrecision=" + columnPrecision);
        System.out.println("columnByteLength=" + columnByteLength);
        System.out.println("columnScale=" + columnScale);
        System.out.println("columnRadix=" + columnRadix);
        System.out.println("columnNullable=" + columnNullable);
        System.out.println("columnRemarks=" + columnRemarks);
    }//from   w w w.j a  va 2s  . c o m

    st.close();
    conn.close();
}