上一个博客说到 statement的返回值是一个ResultSet 那么现在就来分享一下对于ResultSet我们怎么用 怎么获取里面的值
//Jdbc3ResultSet
public class Jdbc3ResultSet {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//1.注册驱动 忘记一点,这个驱动的"com.mysql.jdbc.Driver" 是我们在写代码的时候导的一个包
Class.forName("com.mysql.jdbc.Driver");
//创建一个 Properties对象
//用来存储参数,用户名密码 用户名是你电脑的用户名 密码当然就是你自己的密码了
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "111111");
//2.获得连接数据库对象
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", properties);
//3.获得用于执行sql语句的 Statement 对象
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT *FROM stu ");
//输出当前的resultSet指针所在的位置
System.out.println(resultSet.getRow());
//next后的位置
resultSet.next();
System.out.println(resultSet.getRow());
//previous后的位置 上一行的意思
resultSet.previous();
System.out.println(resultSet.getRow());
//我们想要取到resultSet的值的话用resultSet.next()一行一行的进行取值
while (resultSet.next()) {
System.out.println("id:"
// + resultSet.getInt("id")
//不知道是什么类型的情况下可以用
+ resultSet.getObject(1)
+ "name: " + resultSet.getString("name")
+ "age: " + resultSet.getInt("age"));
}
}
}