JDBC-ResultSet基本使用
ResultSet:结果集对象 封装查询结果
- next():游标向下移动一行 判断当前行是否是最后一行末尾(是否有数据) 如果是 则返回false 如果不是则放回true
- getxxx(参数):获取数据
- xxx:代表数据类型 如:int getInt(),String getString()
- 参数:
- int:代表列的编号 从1开始 如:getString(1)
- String:代表列名称 如:getDouble("balance")
代码案例:
public static void main(String[] args) {
// 创建变量并设为空
Connection conn = null;
Statement stmt = null;
ResultSet res=null;
try {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 定义SQL语句
String sql = "SELECT * FROM account";
// 获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql:///videopractice", "root", "root");
// 获取执行SQL的对象 statement
stmt = conn.createStatement();
// 执行sql
// 影响行数
res = stmt.executeQuery(sql);
// 处理结果
// 让游标向下移动一行
res.next();
// 获取数据
int id = res.getInt(1);
String name = res.getString("name");
double balance = res.getDouble(3);
System.out.println(id+"---"+name+"---"+balance);
// 处理结果
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
// 释放资源
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (res != null) {
try {
res.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
运行结果

注意:
1.游标向下移动一行
2.判断是否有数据
3.获取数据
遍历结果集
代码案例:
public static void main(String[] args) {
// 创建变量并设置为空
Connection conn = null;
Statement stmt = null;
ResultSet res = null;
try {
// 1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 定义SQL语句
String sql = "SELECT * FROM account";
// 获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql:///videopractice", "root", "root");
// 获取执行SQL的对象 statement
stmt = conn.createStatement();
// 执行sql
res = stmt.executeQuery(sql);
// 处理结果
// 让游标向下移动一行
while (res.next()) {
// 获取数据
int id = res.getInt(1);
String name = res.getString("name");
double balance = res.getDouble(3);
System.out.println(id + "---" + name + "---" + balance);
}
// 处理结果
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
// 释放资源
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (res != null) {
try {
res.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
运行结果

测试


浙公网安备 33010602011771号