Home  >  Q&A  >  body text

jdbc - java中,数据库返回一个空的结果集,并赋给变量去调用构造函数,生成的对象是null还是什么?

ResultSet rs= pstmt.executeQuery();//数据库返回一个结果集,现在假设select的是
                                     数据库中没有的数据,那么结果集为空
    while (rs.next())
    {
        String str = rs.getString("Name");//此时str应该是null?
        int id = rs.getInt("Id");     //id为0?
        A a= new A(id,str);  //调用构造函数(定义见第二段代码),那a是什么?是
                               null?此构造器还会被调用吗?a这个对象会生成吗?
public final class A   //这个是A类的定义,成员变量和构造函数
{
private int id;
private String name;

public A(int Id,String Word)
  {
    this.id = Id;
    this.name = Word;
  }
}

我现在项目中要通过a这个对象来判断数据库返回的是否为空集,请问该如何判断?由此引出了上述问题(具体问题可以看代码段的注释)

PHP中文网PHP中文网2741 days ago499

reply all(3)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:36:25

    If the database has an empty set, rs.next() will return false and the while will not be executed.
    If you don’t know, it’s much faster to try out an empty data sheet than to type so many words and post a question here to solve the problem, right?

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 09:36:25

    @min The superficial problem has been solved, but I think the question you asked has not been completely solved. I still suggest that the question owner pays attention to new What the keyword does:

    1. Create space in the heap memory to store A instances

    2. Call the constructor of A

    3. Open an address on the virtual machine stack and point the address to the heap space just opened

    Finally A a = new A(...) 得到就是一个栈引用,这个栈引用不会为空,除非你的 JVM died...

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:36:25

    1.rs.next is wrong, it should be rs.hasNext(), and the result is also empty.
    2. If null and 0 parameters are passed in, the object still needs to be generated. There is no reason not to generate it, what do you think? Thought why not?

    reply
    0
  • Cancelreply