Example usage for java.sql ResultSet next

List of usage examples for java.sql ResultSet next

Introduction

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

Prototype

boolean next() throws SQLException;

Source Link

Document

Moves the cursor forward one row from its current position.

Usage

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   www .  j  av  a  2  s  .c o m*/

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

From source file:Main.java

public static void main(String args[]) throws Exception {
    String URL = "jdbc:microsoft:sqlserver://yourServer:1433;databasename=pubs";
    String userName = "yourUser";
    String password = "yourPassword";

    Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
    Connection con = DriverManager.getConnection(URL, userName, password);
    CallableStatement callstmt = con
            .prepareCall("INSERT INTO myIdentTable (col2) VALUES (?);SELECT @@IDENTITY");
    callstmt.setString(1, "testInputBatch");
    callstmt.execute();/*www  . j a va2 s. com*/

    int iUpdCount = callstmt.getUpdateCount();
    boolean bMoreResults = true;
    ResultSet rs = null;
    int myIdentVal = -1; // to store the @@IDENTITY

    while (bMoreResults || iUpdCount != -1) {
        rs = callstmt.getResultSet();
        if (rs != null) {
            rs.next();
            myIdentVal = rs.getInt(1);
        }
        bMoreResults = callstmt.getMoreResults();
        iUpdCount = callstmt.getUpdateCount();
    }
    callstmt.close();
    con.close();
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Connection conn = getConnection();
    Statement stmt = null;/* ww  w.ja v a2s  .  co  m*/
    ResultSet rs = null;
    conn = getConnection();
    stmt = conn.createStatement();
    stmt.executeUpdate("insert into animals_table (name) values('newName')");
    rs = stmt.getGeneratedKeys();
    while (rs.next()) {
        ResultSetMetaData rsMetaData = rs.getMetaData();
        int columnCount = rsMetaData.getColumnCount();

        for (int i = 1; i <= columnCount; i++) {
            String key = rs.getString(i);
            System.out.println("key " + i + " is " + key);
        }
    }
    rs.close();
    stmt.close();
    conn.close();
}

From source file:GetDBInfo.java

public static void main(String[] args) {
    Connection c = null; // The JDBC connection to the database server
    try {/*  w  w  w  .  ja va  2s  . com*/
        // Look for the properties file DB.props in the same directory as
        // this program. It will contain default values for the various
        // parameters needed to connect to a database
        Properties p = new Properties();
        try {
            p.load(GetDBInfo.class.getResourceAsStream("DB.props"));
        } catch (Exception e) {
        }

        // Get default values from the properties file
        String driver = p.getProperty("driver"); // Driver class name
        String server = p.getProperty("server", ""); // JDBC URL for server
        String user = p.getProperty("user", ""); // db user name
        String password = p.getProperty("password", ""); // db password

        // These variables don't have defaults
        String database = null; // The db name (appended to server URL)
        String table = null; // The optional name of a table in the db

        // Parse the command-line args to override the default values above
        for (int i = 0; i < args.length; i++) {
            if (args[i].equals("-d"))
                driver = args[++i]; //-d <driver>
            else if (args[i].equals("-s"))
                server = args[++i];//-s <server>
            else if (args[i].equals("-u"))
                user = args[++i]; //-u <user>
            else if (args[i].equals("-p"))
                password = args[++i];
            else if (database == null)
                database = args[i]; // <dbname>
            else if (table == null)
                table = args[i]; // <table>
            else
                throw new IllegalArgumentException("Unknown argument: " + args[i]);
        }

        // Make sure that at least a server or a database were specified.
        // If not, we have no idea what to connect to, and cannot continue.
        if ((server.length() == 0) && (database.length() == 0))
            throw new IllegalArgumentException("No database specified.");

        // Load the db driver, if any was specified.
        if (driver != null)
            Class.forName(driver);

        // Now attempt to open a connection to the specified database on
        // the specified server, using the specified name and password
        c = DriverManager.getConnection(server + database, user, password);

        // Get the DatabaseMetaData object for the connection. This is the
        // object that will return us all the data we're interested in here
        DatabaseMetaData md = c.getMetaData();

        // Display information about the server, the driver, etc.
        System.out.println("DBMS: " + md.getDatabaseProductName() + " " + md.getDatabaseProductVersion());
        System.out.println("JDBC Driver: " + md.getDriverName() + " " + md.getDriverVersion());
        System.out.println("Database: " + md.getURL());
        System.out.println("User: " + md.getUserName());

        // Now, if the user did not specify a table, then display a list of
        // all tables defined in the named database. Note that tables are
        // returned in a ResultSet, just like query results are.
        if (table == null) {
            System.out.println("Tables:");
            ResultSet r = md.getTables("", "", "%", null);
            while (r.next())
                System.out.println("\t" + r.getString(3));
        }

        // Otherwise, list all columns of the specified table.
        // Again, information about the columns is returned in a ResultSet
        else {
            System.out.println("Columns of " + table + ": ");
            ResultSet r = md.getColumns("", "", table, "%");
            while (r.next())
                System.out.println("\t" + r.getString(4) + " : " + r.getString(6));
        }
    }
    // Print an error message if anything goes wrong.
    catch (Exception e) {
        System.err.println(e);
        if (e instanceof SQLException)
            System.err.println(((SQLException) e).getSQLState());
        System.err.println("Usage: java GetDBInfo [-d <driver] " + "[-s <dbserver>]\n"
                + "\t[-u <username>] [-p <password>] <dbname>");
    }
    // Always remember to close the Connection object when we're done!
    finally {
        try {
            c.close();
        } catch (Exception e) {
        }
    }
}

From source file:Example.java

public static void main(String args[]) {
    try {/*from  ww  w  .  j a v a2  s  . c o  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[]) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.newDocument();
    Element results = doc.createElement("Results");
    doc.appendChild(results);/*from   w  w  w  .j  a va  2 s .  co m*/

    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con = DriverManager
            .getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/access.mdb");

    ResultSet rs = con.createStatement().executeQuery("select * from product");

    ResultSetMetaData rsmd = rs.getMetaData();
    int colCount = rsmd.getColumnCount();

    while (rs.next()) {
        Element row = doc.createElement("Row");
        results.appendChild(row);
        for (int i = 1; i <= colCount; i++) {
            String columnName = rsmd.getColumnName(i);
            Object value = rs.getObject(i);
            Element node = doc.createElement(columnName);
            node.appendChild(doc.createTextNode(value.toString()));
            row.appendChild(node);
        }
    }
    DOMSource domSource = new DOMSource(doc);
    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer transformer = tf.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);
    transformer.transform(domSource, sr);

    System.out.println(sw.toString());

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

From source file:geocodingsql.Main.java

/**
 * @param args the command line arguments
 *//*  w  w  w  .ja v a2s .c  om*/
public static void main(String[] args) throws JSONException {
    Main x = new Main();
    ResultSet rs = null;
    String string = "";

    x.establishConnection();
    rs = x.giveName();

    try {
        while (rs.next()) {
            string += rs.getString(1) + " ";
        }

        JOptionPane.showMessageDialog(null, string, "authors", 1);
    } catch (Exception e) {
        System.out.println("Problem when printing the database.");
    }
    x.closeConnection();

    // Now do Geocoding
    String req = "https://maps.googleapis.com/maps/api/geocode/json?latlng=41.3166662867211,-72.9062497615814&result_type=point_of_interest&key="
            + key;
    try {
        URL url = new URL(req + "&sensor=false");
        URLConnection conn = url.openConnection();
        ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
        IOUtils.copy(conn.getInputStream(), output);
        output.close();
        req = output.toString();
    } catch (Exception e) {
        System.out.println("Geocoding Error");
    }
    JSONObject jObject = new JSONObject(req);
    JSONArray resultArray = jObject.getJSONArray("results");
    //this prints out the neighborhood of the provided coordinates
    System.out.println(resultArray.getJSONObject(0).getJSONArray("address_components")
            .getJSONObject("neighborhood").getString("long_name"));
}

From source file:BatchUpdate.java

public static void main(String args[]) {
    String url = "jdbc:mySubprotocol:myDataSource";
    Connection con;// www .  j  av  a  2s  .  c om
    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);
        con.setAutoCommit(false);
        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();
        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("SQLException: " + b.getMessage());
        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] + " ");
        }

    } 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:ImageStringToBlob.java

public static void main(String[] args) {
    Connection conn = null;//w  w  w.j a  v a 2 s . c o  m

    if (args.length != 1) {
        System.out.println("Missing argument: full path to <oscar.properties>");
        return;
    }

    try {

        FileInputStream fin = new FileInputStream(args[0]);
        Properties prop = new Properties();
        prop.load(fin);

        String driver = prop.getProperty("db_driver");
        String uri = prop.getProperty("db_uri");
        String db = prop.getProperty("db_name");
        String username = prop.getProperty("db_username");
        String password = prop.getProperty("db_password");

        Class.forName(driver);
        conn = DriverManager.getConnection(uri + db, username, password);
        conn.setAutoCommit(true); // no transactions

        /*
         * select all records ids with image_data not null and contents is null
         * for each id fetch record
         * migrate data from image_data to contents
         */
        String sql = "select image_id from client_image where image_data is not null and contents is null";
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        List<Long> ids = new ArrayList<Long>();

        while (rs.next()) {
            ids.add(rs.getLong("image_id"));
        }

        rs.close();

        sql = "select image_data from client_image where image_id = ?";
        pst = conn.prepareStatement(sql);

        System.out.println("Migrating image data for " + ids.size() + " images...");
        for (Long id : ids) {
            pst.setLong(1, id);
            ResultSet imagesRS = pst.executeQuery();
            while (imagesRS.next()) {
                String dataString = imagesRS.getString("image_data");
                Blob dataBlob = fromStringToBlob(dataString);
                if (writeBlobToDb(conn, id, dataBlob) == 1) {
                    System.out.println("Image data migrated for image_id: " + id);
                }
            }
            imagesRS.close();
        }
        System.out.println("Migration completed.");

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    ResultSet resultSet = null;
    Class.forName(DRIVER);/*from  ww w .  j a  v a  2s . 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();
}