JDBC之——ResultSet结果集

一、ResultSet结果集的引入

当我们查询数据库时,返回的是一个二维的结果集,我们这时候需要使用ResultSet来遍历结果集,获取每一行的数据。

二、使用ResultSet遍历查询结果

boolean next()将光标从当前位置向前移一行。

String getString(int columnInex) 以Java编程语言中String的形式获取此ResultSet对象的当前行中指定列的值。

String getString(String columnLabel)以Java编程语言中String的形式获取此ResultSet对下岗的当前行中指定列的值。

方法一:一般开发不用

public class Demo01 {
	
	private static DbUtil dbUtil = new DbUtil();
	private static void listBook() throws Exception{
		Connection con = dbUtil.getCon();//获取连接
		String sql = "select * from t_book";
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();//返回结果集ResultSet
		while(rs.next()) {
			int id = rs.getInt(1);//获取第一个列岛值  编号:id
			String bookName = rs.getString(2);
			float price = rs.getFloat(3);
			String author = rs.getString(4);
			int bookTypeId = rs.getInt(5);
			System.out.println(id + "   " +bookName+"   "+price+"   "+author+"   "+ bookTypeId);
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		listBook();
	}
}

方法二:一般用以下方法,可读性比较好

public class Demo02 {
	
	private static DbUtil dbUtil = new DbUtil();
	private static void listBook2() throws Exception{
		Connection con = dbUtil.getCon();//获取连接
		String sql = "select * from t_book";
		PreparedStatement pstmt = con.prepareStatement(sql);
		ResultSet rs = pstmt.executeQuery();//返回结果集ResultSet
		while(rs.next()) {
			int id = rs.getInt("id");//获取第一个列岛值  编号:id
			String bookName = rs.getString("bookName");
			float price = rs.getFloat("price");
			String author = rs.getString("author");
			int bookTypeId = rs.getInt("bookTypeId");
			System.out.println(id + "   " +bookName+"   "+price+"   "+author+"   "+ bookTypeId);
		}
		
	}
	
	public static void main(String[] args) throws Exception {
		listBook2();
	}
}

猜你喜欢

转载自blog.csdn.net/weixin_39941298/article/details/81100932