Gray Adams
Gray Adams

Reputation: 4117

Get Array From List Of Rows?

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

Upvotes: 0

Views: 2644

Answers (1)

beerbajay
beerbajay

Reputation: 20270

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.

Upvotes: 3

Related Questions