今天老实犯糊涂,再总结一下以前的知识吧~

executeQuery()永远不会返回null

这一点很重要,也很容易让人忽视。举个例子吧;
比如,在数据库中,只有两个用户user1,user2的密码是“123”。那么运行下面代码的结果是什么呢?

......

                String sql = "select uname from user where  upwd = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, "123");
		ResultSet rs = null;
		rs = pst.executeQuery();//此时rs里面有两条数据
		System.out.println(rs.next());//<font color=red>不是打印user1,而是打印true</font>
		System.out.println(rs.next());//不是打印user2,而是打印true
		System.out.println(rs.next());//打印false,由于每次调用next()的作用是向后移动一条数据,所以现在已经到了第三条数据,而rs里面一共有两条数据
		
......

那么如果想得到user1,user2,该怎么办呢?如下:

......

                String sql = "select uname from user where  upwd = ?";
		PreparedStatement pst = conn.prepareStatement(sql);
		pst.setString(1, "123");
		ResultSet rs = null;
		rs = pst.executeQuery();//此时rs里面有两条数据
		
		while(rs.next()){
			System.out.println(rs.getString("uname"));//这样就能输出user1,user2了
		}
......

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2021-07-17
  • 2021-04-27
  • 2021-09-02
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-07-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
  • 2021-11-09
相关资源
相似解决方案