简体   繁体   中英

Formatting data from a result set with the toString() method

My question is this, what is the most efficient way to use the toString method to format data from a ResultSet?

Here is the method that I have thus far:

public void query()
{
    Statement stmt = null;
    ResultSet rs = null;

    try
    {
        //Create database connection
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/registrar",
                "abt1s", "abt1s");
        stmt = conn.createStatement();

        //create SQL statement
        String st = "SELECT * FROM  student WHERE studentID = '" + this.getStudentID() + " '";

        rs = stmt.executeQuery(st);

        String studentData = rs.toString();
        System.out.println(studentData);

        rs.close();
        stmt.close();
        conn.close();
    }catch(Exception e)
            {
                System.err.println("ERROR: Either cannot connect to the DB " + " or error with the SQL statement");
            }

}

You can go row by row through the ResultSet and print whatever you want:

// Fetch each row from the result set
while (rs.next()) {
    // Get the data from the row using the column index
    String s = rs.getString(1);

    // Get the data from the row using the column name
    s = rs.getString("col_string");
}

You need to convert the ResultSet into a Student class before you can use Student.toString to generate the proper output.

"Retrieving and Modifying Values from Result Sets" explains one way of extracting data from a ResultSet .

Alternatively, you can look at an Object-Relational-Mapping (ORM) which eases creating domain objects (like Student ) from database rows. What Java ORM do you prefer, and why? has useful pointers to discussions of the various ORMs and how to get started with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM