JDBC各个详解-ResultSet基本使用
ResultSet:结果集对象,封装查询结果
next():游标向下移动一行
getxxx():获取数据
xxx:代表数据类型 如:int getInt() String getString()
参数:
1.int:代表列的编号,从1开始 如:getInt(1)
2.String:列的名称,如:getString("name")
代码:
public static void main(String[] args) { Connection conn = null; Statement state = null; ResultSet set = null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //定义sql String sql = "select * from account"; //获取执行sql对象 state = conn.createStatement(); //执行sql set = state.executeQuery(sql); //处理数据 //让游标向下移动一行 set.next(); int id = set.getInt(1); String name = set.getString("name"); double banlance = set.getDouble(3); System.out.println(id + "-----" + name + "-----" + banlance); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SQLException e) { throw new RuntimeException(e); }finally { //释放资源 if (set != null){ try { set.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (state != null){ try { state.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
运行结果:
注意:
使用步骤:
1.游标向下移动一行
2.判断是否有数据
3.获取数据
next():游标向下移动一行,判断当前行是否是最后一行末尾(是否有数据)
public static void main(String[] args) { Connection conn = null; Statement state = null; ResultSet set = null; try { //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //获取连接对象 conn = DriverManager.getConnection("jdbc:mysql:///db2", "root", "root"); //定义sql String sql = "select * from account"; //获取执行sql对象 state = conn.createStatement(); //执行sql set = state.executeQuery(sql); //处理数据 //循环判断游标是否是最后一行末尾数据 while (set.next()){//next():下一行 int id = set.getInt(1); String name = set.getString("name"); double banlance = set.getDouble(3); System.out.println(id + "-----" + name + "-----" + banlance); } } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (SQLException e) { throw new RuntimeException(e); }finally { //释放资源 if (set != null){ try { set.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (state != null){ try { state.close(); } catch (SQLException e) { throw new RuntimeException(e); } } if (conn != null){ try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } } }
运行结果:
标签:遍历,RuntimeException,ResultSet,state,set,JDBC,new,null,throw From: https://www.cnblogs.com/qihaokuan/p/16810213.html