Java 使用toString()方法格式化结果集中的数据
我的问题是,使用toString方法格式化ResultSet中的数据最有效的方法是什么 以下是我迄今为止采用的方法:Java 使用toString()方法格式化结果集中的数据,java,jdbc,Java,Jdbc,我的问题是,使用toString方法格式化ResultSet中的数据最有效的方法是什么 以下是我迄今为止采用的方法: public void query() { Statement stmt = null; ResultSet rs = null; try { //Create database connection Connection conn = DriverManager.getConnection("jdbc:mysql
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");
}
在使用
Student.toString
生成正确的输出之前,需要将ResultSet
转换为Student
类
解释从结果集
提取数据的一种方法
或者,您可以查看对象关系映射(ORM),它可以简化从数据库行创建域对象(如
Student
)。有一些有用的指针指向各种ORM的讨论以及如何开始使用它们。您希望在输出中看到什么?为什么您认为这对您的使用不够有效?“从student中选择*其中studentID=”+this.getStudentID()+”代码>是一个潜在的。请养成使用准备好的语句的习惯。当一条语句失败并出现SQLException
时,代码会使SQL连接保持打开状态。可能会将结束代码放在finally
块中。我了解准备好的语句。我会做出改变。我的代码返回结果集的散列。我需要做的是,使用重写的toString方法打印rs中包含的数据。示例中没有包含这一点,但我认为我已经正确地编写了它。您的toString
方法是在什么类上定义的?返回的ResultSet
的实现由JDBC驱动程序决定,而不是由您的代码决定,因此您可以将其传递给静态
方法,该方法将其转换为字符串
,但除非您实现自己的驱动程序
包装器,您几乎无法控制rs.toString的功能。我已经尝试过了,它确实从结果集中获取了数据。我会继续使用这个。我如何使用toString方法格式化它?因为ResultSet类不是您自己的类,所以您不能更改它的方法。最好是编写一个静态方法,该方法接收ResultSet参数并返回字符串。基本上,我应该实现toString方法来格式化数据并打印到屏幕上。我只是很难看到这是怎么做到的。