Example usage for java.sql ResultSet getString

List of usage examples for java.sql ResultSet getString

Introduction

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

Prototype

String getString(String columnLabel) throws SQLException;

Source Link

Document

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

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ResultSet resultSet = null;
    Class.forName(DRIVER);/* w  w  w  .j a  v  a2  s.  c  o m*/
    Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

    DatabaseMetaData metadata = connection.getMetaData();
    resultSet = metadata.getTypeInfo();
    while (resultSet.next()) {
        String typeName = resultSet.getString("TYPE_NAME");
        System.out.println("Type Name = " + typeName);
    }
    resultSet.close();
    connection.close();
}

From source file:TableTypes.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;/*from ww  w. j a  va2s. c o  m*/

    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");

        DatabaseMetaData dbmd = con.getMetaData();
        String dbmsName = dbmd.getDatabaseProductName();
        ResultSet rs = dbmd.getTableTypes();
        System.out.print("The following types of tables are ");
        System.out.println("available in " + dbmsName + ":  ");

        while (rs.next()) {
            String tableType = rs.getString("TABLE_TYPE");
            System.out.println("    " + tableType);
        }

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

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

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 meta = conn.getMetaData();
    // The '_' character represents any single character.
    // The '%' character represents any sequence of zero
    // or more characters.
    ResultSet rs = meta.getBestRowIdentifier(conn.getCatalog(), null, "survey",
            DatabaseMetaData.bestRowTemporary, false);
    while (rs.next()) {

        short actualScope = rs.getShort("SCOPE");
        String columnName = rs.getString("COLUMN_NAME");
        int dataType = rs.getInt("DATA_TYPE");
        String typeName = rs.getString("TYPE_NAME");
        int columnSize = rs.getInt("COLUMN_SIZE");
        short decimalDigits = rs.getShort("DECIMAL_DIGITS");
        short pseudoColumn = rs.getShort("PSEUDO_COLUMN");

        System.out.println("tableName=survey");
        System.out.println("scope=" + actualScope);
        System.out.println("columnName=" + columnName);
        System.out.println("dataType=" + dataType);
        System.out.println("typeName" + typeName);
        System.out.println("columnSize" + columnSize);
        System.out.println("decimalDigits" + decimalDigits);
        System.out.println("pseudoColumn" + pseudoColumn);
    }/*w  ww .  ja  v  a  2 s  . c  o m*/

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

From source file:Select.java

public static void main(String args[]) {
    String url = "jdbc:msql://carthage.imaginary.com/ora";
    Connection con = null;/*w ww  .ja va 2  s  .c  om*/

    try {
        String driver = "com.imaginary.sql.msql.MsqlDriver";

        Class.forName(driver).newInstance();
    } catch (Exception e) {
        System.out.println("Failed to load mSQL driver.");
        return;
    }
    try {
        con = DriverManager.getConnection(url, "borg", "");
        Statement select = con.createStatement();
        ResultSet result = select.executeQuery("SELECT test_id, test_val FROM test");

        System.out.println("Got results:");
        while (result.next()) { // process results one row at a time
            int key = result.getInt(1);
            String val = result.getString(2);

            System.out.println("key = " + key);
            System.out.println("val = " + val);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (con != null) {
            try {
                con.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:SetSavepoint.java

public static void main(String args[]) {

    String url = "jdbc:mySubprotocol:myDataSource";

    try {/*  www .  java  2s .c o m*/

        Class.forName("myDriver.className");

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

    try {

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

        String query = "SELECT COF_NAME, PRICE FROM COFFEES " + "WHERE TOTAL > ?";
        String update = "UPDATE COFFEES SET PRICE = ? " + "WHERE COF_NAME = ?";

        PreparedStatement getPrice = con.prepareStatement(query);
        PreparedStatement updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 7000);
        ResultSet rs = getPrice.executeQuery();

        Savepoint save1 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save1);
            }

        }

        getPrice = con.prepareStatement(query);
        updatePrice = con.prepareStatement(update);

        getPrice.setInt(1, 8000);

        rs = getPrice.executeQuery();
        System.out.println();

        Savepoint save2 = con.setSavepoint();

        while (rs.next()) {
            String cof = rs.getString("COF_NAME");
            float oldPrice = rs.getFloat("PRICE");
            float newPrice = oldPrice + (oldPrice * .05f);
            updatePrice.setFloat(1, newPrice);
            updatePrice.setString(2, cof);
            updatePrice.executeUpdate();
            System.out.println("New price of " + cof + " is " + newPrice);
            if (newPrice > 11.99) {
                con.rollback(save2);
            }
        }

        con.commit();

        Statement stmt = con.createStatement();
        rs = stmt.executeQuery("SELECT COF_NAME, " + "PRICE FROM COFFEES");

        System.out.println();
        while (rs.next()) {
            String name = rs.getString("COF_NAME");
            float price = rs.getFloat("PRICE");
            System.out.println("Current price of " + name + " is " + price);
        }

        con.close();

    } catch (Exception 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);
    }//w w w  .j  av  a2s.co  m

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

From source file:MainClass.java

public static void main(String args[]) {
    Connection conn = null;/*from ww  w.j  a  v  a2  s  . c  o  m*/
    Statement stmt = null;
    ResultSet rs = null;
    try {
        conn = getConnection();
        stmt = conn.createStatement();
        String query = "select EmployeeID, LastName, FirstName from Employees";
        rs = stmt.executeQuery(query);
        while (rs.next()) {
            System.out.println(rs.getString("EmployeeID") + " " + rs.getString("LastName") + " "
                    + rs.getString("FirstName"));
        }
    } catch (Exception e) {
        // handle the exception
        e.printStackTrace();
        System.err.println(e.getMessage());
    } finally {
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (Exception ee) {
            ee.printStackTrace();
        }
    }
}

From source file:BatchUpdate.java

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

    ResultSet rs = null;//from  w  ww.j  a  v  a2s .  co m
    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:Example.java

public static void main(String args[]) {
    try {/*ww w  . j ava 2 s .  co m*/
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

        Connection con = DriverManager.getConnection("jdbc:odbc:inventory", "", "");
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery("SELECT * FROM inventory ORDER BY price");

        ResultSetMetaData rsmd = rs.getMetaData();
        int numberOfColumns = rsmd.getColumnCount();
        int rowCount = 1;
        while (rs.next()) {
            for (int i = 1; i <= numberOfColumns; i++) {
                System.out.print(rs.getString(i) + " ");
            }
            rowCount++;
        }
        stmt.close();
        con.close();
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:Main.java

public static void main(String[] args) {
    Connection conn = null;/*w  w  w.  ja v  a2s .c  om*/
    Statement stmt = null;
    try {
        // Register JDBC driver
        Class.forName(JDBC_DRIVER);

        // Open a connection
        System.out.println("Connecting to database...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);

        // Execute a query
        System.out.println("Creating statement...");
        stmt = conn.createStatement();
        String sql;
        sql = "SELECT id, first, last, age FROM Employees";
        stmt.executeUpdate(
                "CREATE TABLE Employees ( id INTEGER IDENTITY, first VARCHAR(256),  last VARCHAR(256),age INTEGER)");
        stmt.executeUpdate("INSERT INTO Employees VALUES(1,'Jack','Smith', 100)");

        ResultSet rs = stmt.executeQuery(sql);

        // Extract data from result set
        while (rs.next()) {
            // Retrieve by column name
            int id = rs.getInt("id");
            int age = rs.getInt("age");
            String first = rs.getString("first");
            String last = rs.getString("last");

            System.out.print("ID: " + id);
            System.out.print(", Age: " + age);
            System.out.print(", First: " + first);
            System.out.println(", Last: " + last);
        }
        // Clean-up environment
        rs.close();
        stmt.close();
        conn.close();
    } catch (SQLException se) {
        se.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        // finally block used to close resources
        try {
            if (stmt != null)
                stmt.close();
        } catch (SQLException se2) {
        }
        try {
            if (conn != null)
                conn.close();
        } catch (SQLException se) {
            se.printStackTrace();
        }
    }
    System.out.println("Goodbye!");
}