使用 ResultSet 遍历查询结果(返回list结果集,重新toString()方法)


package chap05.sec02;


import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


import model.Book;
import util.DbUtil;


public class Demo2 {
private static DbUtil dbUtil=new DbUtil();
public static List listBook() throws SQLException{
List list=new ArrayList();
Connection con=dbUtil.getCon();
String sql="select * from t_book";
PreparedStatement pstmt=con.prepareStatement(sql);
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
int id=rs.getInt("id");
String bookName=rs.getString("bookName");
float price=rs.getFloat("price");
String author=rs.getString("author");
int bookTypeId=rs.getInt("bookTypeId");
Book book=new Book(id,bookName,price,author,bookTypeId);
list.add(book);

}
return list;

}
public static void main(String[] args) throws SQLException {
// TODO Auto-generated method stub
List list=listBook();
for (Book book : list) {
System.out.println(book);
}
}


}

你可能感兴趣的:(JDBC,使用,ResultSet,遍历查询结果,重新toString方法)