案例:演示如何使用ResultSet对象滚动读取结果集中的数据

public class Example03 {
	public static void main(String[] args) {
		    Connection conn = null;
			Statement stmt = null;
			try {
			   Class.forName("com.mysql.jdbc.Driver");
			   String url = "jdbc:mysql://localhost:3306/jdbc";
			   String username = "root";
			   String password = "root";
			   //1.获取Connection对象
			   conn = DriverManager.getConnection(url, username, password);
			   String sql = "select * from users";
			   //2.创建Statement对象并设置常量
	           Statement st =conn.createStatement(
						ResultSet.TYPE_SCROLL_INSENSITIVE, 
						ResultSet.CONCUR_READ_ONLY);
	           //3.执行SQL并将获取的数据信息存放在ResultSet中
				ResultSet rs = st.executeQuery(sql);
			   //4.取出ResultSet中指定数据的信息
				System.out.print("第2条数据的name值为:");
				rs.absolute(2);        //将指针定位到结果集中第2行数据
				System.out.println(rs.getString("name"));
				System.out.print("第1条数据的name值为:");
				rs.beforeFirst();      //将指针定位到结果集中第1行数据之前
				rs.next();              //将指针向后滚动
				System.out.println(rs.getString("name"));
				System.out.print("第4条数据的name值为:");
				rs.afterLast();        //将指针定位到结果集中最后一条数据之后
				rs.previous();         //将指针向前滚动
				System.out.println(rs.getString("name"));
			} catch (Exception e) {
				e.printStackTrace();
			} finally { // 释放资源
				if (stmt != null) {
					try {
						stmt.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
					stmt = null;
				}
				if (conn != null) {
					try {
						conn.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
					conn = null;
				}
			}
		}
	}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值