JDBC各个类详解-ResultSet-遍历结果集和JDBC工具类
ResultSet-遍历结果集
注意:
使用步骤:
1、游标向下移动一行
2、判断是否有数据
3、获取数据
// 循环判断游标是否是最后一行末尾 while(rs.next()){ // 获取数据 int id = rs.getInt(1); String name = rs.getDouble(3); double balance = rs.getDouble(3); System.out.println(id + “---” + name + “---” + balance); }
JDBC工具类
目的:简化书写
分析:
1.注册驱动也抽取
2.抽取一个方法获取连接对象
需求:不想传递参数(麻烦),还得保证工具类的通用性
解决:配置文件
jdbc.properties
url=
user=
password=
3.抽取一个方法释放资源
配置文件
url=jdbc:mysql:///videopractice user=root password=root driver=com.mysql.cj.jdbc.Driver
工具类:
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 文件的读取 只需要读取一次即可拿到这些值 使用静态代码块
*/
static {
// 读取资源文件 获取值
try {
// 1.创建Properties集合类
Properties pro = new Properties();
// 2.加载文件
pro.load(new FileReader("src\\main\\resources\\jdbc.properties"));
// 3.获取数据 赋值
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// 4.注册驱动
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取连接
*
* @return 连接对象
*/
public static Connection getConnection(String url, String user, String password) throws SQLException {
return DriverManager.getConnection(url, user, password);
}
/**
* 释放资源
*
* @param stmt
* @param conn
*/
public static void close(Statement stmt, Connection conn) {
if (stmt != null) {
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
演示工具类:
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet res = null;
try {
/* //1.注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取Connection对象
conn = DriverManager.getConnection("jdbc:mysql:///videopractice", "root", "root");*/
conn = JDBCUtil.getConnection();
// 定义SQL语句
String sql = "SELECT * FROM account";
// 获取执行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 (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();
}
} */
JDBCUtil.close(stmt,conn);
}
运行结果


浙公网安备 33010602011771号