ResultSet接口基本介绍与应用
基本介绍
1.表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
例如:select语句查询得到的数据表
2.ResultSet对象保持一个光标指向当前的数据行。最初,光标位于第一行之前
3.next方法将光标移动到下一行,并且由于在ResultSet对象中没有更多行时返回false,可以在while循环中使用循环来遍历结果集
应用实例
package Jdbc.myjdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @author zq
* 演示select语句返回ResultSet,并取出结果
*/
public class ResultSet_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//创建配置文件对象
Properties properties = new Properties();
//获取文件中的键值
properties.load(new FileInputStream("src\\Jdbc\\myjdbc\\mysql.properities"));
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Class.forName(driver);
Connection connection = DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
//使用SQL语句
String sql = "select * from actor";
//执行给定的sql语句,该语句返回单个ResultSet对象
ResultSet resultSet = statement.executeQuery(sql);
//使用while循环取出数据
while (resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String sex = resultSet.getString(3);
Date date = resultSet.getDate(4);
System.out.println(id +"\t"+ name + "\t" + sex +"\t"+ date + "\t");
}
//关闭资源
resultSet.close();
connection.close();
statement.close();
}
}