JDBC中的ResultSet结果集详解

it2022-05-05  115

遍历结果集(游标)获取记录;

import java.sql.*; public class ResultSetDemo { public static void main(String[] args) throws SQLException { Connection con = null; Statement statement = null; ResultSet res =null; try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1", "root", "admin"); String sql = "select * from account"; statement = con.createStatement(); res = statement.executeQuery(sql); // if(res.next()){ // res.next(); // System.out.println(res.getInt(1)); // System.out.println(res.getString("name")); // System.out.println(res.getInt(3)); // } //循环判断结果集是否有下一行,获取数据 //循环判断游标是否是最后一行末尾,如果不是就进入while循环获取数据并打印数据, while (res.next()){ System.out.print(res.getInt(1)); System.out.print(res.getString("name")); System.out.println(res.getInt(3)); System.out.println("========================"); } } catch (SQLException e) { e.printStackTrace(); }finally { res.close(); statement.close(); con.close(); } } }

查询表对象 将其封装成对象,装在在集合中;

public class Dept { private int id; private String dname; private String loc; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } @Override public String toString() { return "Dept{" + "id=" + id + ", dname='" + dname + '\'' + ", loc='" + loc + '\'' + '}'; } } import java.sql.*; import java.util.ArrayList; import java.util.List; public class ResultSetConDept { public static void main(String[] args) throws SQLException { List<Dept> list = new ResultSetConDept().exsql(); System.out.println(list); } public List<Dept> exsql() throws SQLException { Connection con = null; Statement stmt =null; Dept dept = null; List<Dept> list = new ArrayList<Dept>(); try { con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1","root","admin"); String sql = "select * from dept"; stmt = con.createStatement(); ResultSet res = stmt.executeQuery(sql); while (res.next()){ int id = res.getInt(1); String dname = res.getString("dname"); String loc = res.getString("loc"); dept = new Dept(); dept.setId(id); dept.setDname(dname); dept.setLoc(loc); //装在集合 list.add(dept); } } catch (SQLException e) { e.printStackTrace(); }finally { stmt.close(); con.close(); } return list; } }

最新回复(0)