JDBC中ResultSet基本使用以及ResultSet遍历结果集
JDBC中ResultSet基本使用以及ResultSet遍历结果集
ResultSet:结果集对象,封装查询结果
next():游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据),如果是则返回false,如果不是则返回true
getXxx(参数):获取数据
Xxx:代表数据类型
参数:
1.int:代表列的编号,从1开始 如:getString(1)
2.String:代表列的名称。 如:getDouble("balance")
/** * ResultSet基本使用 */ public class JDBCDemo06 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db1", "root", "root"); //3.定义sql String sql = "select * from account"; //4.获取执行sql的对象 stmt = conn.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 //让游标向下移动一行 rs.next(); //获取数据 int id = rs.getInt(1); String name = rs.getString("name"); double balance = rs.getDouble(3); System.out.println(id+"----"+name+"----"+balance); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //7.释放资源 if (rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
运行结果:
注意:
使用步骤:
1.游标向下移动一行
2.判断是否有数据
3.获取数据
/** * ResultSet基本使用 */ public class JDBCDemo06 { public static void main(String[] args) { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { //1.注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //2.获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db1", "root", "root"); //3.定义sql String sql = "select * from account"; //4.获取执行sql的对象 stmt = conn.createStatement(); //5.执行sql rs = stmt.executeQuery(sql); //6.处理结果 //让游标向下移动一行 //循环判断游标是否是最后一行末尾 while (rs.next()){ //获取数据 int id = rs.getInt(1); String name = rs.getString("name"); double balance = rs.getDouble(3); System.out.println(id+"----"+name+"----"+balance); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException throwables) { throwables.printStackTrace(); }finally { //7.释放资源 if (rs!=null){ try { rs.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (stmt!=null){ try { stmt.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } if (conn!=null){ try { conn.close(); } catch (SQLException throwables) { throwables.printStackTrace(); } } } } }
运行结果:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?