我的问题是,使用 toString 方法格式化 ResultSet 中的数据的最有效方法是什么?
这是我迄今为止的方法:
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");
}
}
最佳答案
您可以逐行浏览结果集并打印您想要的任何内容:
// 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");
}
关于java - 使用 toString() 方法格式化结果集中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223122/