0

I was curious on how to get a list of rows and add values from each row to an array in Java.

Here is what it looks like in PHP:

<?php
$result = mysql_query("SELECT * FROM names");
while($row = mysql_fetch_array($result)) {
// Get variables from this row and such
}
?>

I can't seem to find out how to do this in Java.

Resolution Found

Statement sta = con.createStatement(); 
ResultSet res = sta.executeQuery("SELECT TOP 10 * FROM SalesLT.Customer");
while (res.next()) {
    String firstName = res.getString("FirstName");
    String lastName = res.getString("LastName");
    System.out.println("   " + firstName + " " + lastName);
}
2
  • 1
    There are a million JDBC tutorials on the web; start there, unless you're using an ORM library. Commented Feb 5, 2012 at 16:11
  • @DaveNewton Could you link me to one? I can't find any for this task. Commented Feb 5, 2012 at 16:14

1 Answer 1

3

If you want to use pure JDBC you can follow the example from the JDBC tutorial:

public void connectToAndQueryDatabase(String username, String password) {
    Connection con = DriverManager.getConnection(
        "jdbc:myDriver:myDatabase", username, password);

    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM Table1");
    while (rs.next()) {
        int x = rs.getInt("a");
        String s = rs.getString("b");
        float f = rs.getFloat("c");
    }
}

But most people don't do this any more; you can, for example, use an ORM like hibernate to abstract the database a bit.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.