package cn.chunzhi.jdbc;
import java.sql.*;
public class Test06_Jdbc_ResultSet_遍历 {
public static void main(String[] args) {
ResultSet rs = null;
Statement stmt = null;
Connection conn = null;
try {
// 1.注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 2.获取数据库连接对象
conn = DriverManager.getConnection("jdbc:mysql://localhost:3305/db2", "root", "root");
// 3.获取执行sql语句的对象
stmt = conn.createStatement();
// 4.定义sql
String sql = "select * from account";
// 5.执行sql
rs = stmt.executeQuery(sql);
// 6.处理结果
// 循环判断游标是否是最后一行末尾
while(rs.next()) {
// 6.1获取数据
int id = rs.getInt(1);
String name = rs.getString("name");
double balance = rs.getDouble(3);
System.out.println(id +"------"+ name +"-----"+ balance);
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
// 7.释放资源
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}