数据库不喜欢从循环中读取值



我有一个java数据库成功连接到我的java代码。这一切都很好,因为它很有效。

当我将数据库中的结果存储到变量中时。。。它工作得很好。

现在我已经做了8次了,我使用了一个循环和一个数组,但是通过使用try-catch工具,它给出了一个错误,错误是:java.lang.NullPointerException

进一步的调查表明,它似乎并不喜欢这个循环。

public String Title []; //in class but out of any methods
    public void gettinginfo ()
    {
        try
        {
            int AB = 0;  //array base starts from 0
            //ID in database starts from 1
            for (int i = 1; i<=8; i++)
            {
                String query = "SELECT * FROM students WHERE ID = " + i;
                Rs = St.executeQuery(query);
                while (Rs.next())
                {   
                    Title[AB] = Rs.getString("StudentName");
                    AB++;
                }
            }
        }
        catch (Exception ex)
        {
            System.out.println("Error is: " + ex);
        }
    }

NullPointerException发生在哪一行?可能您的Title阵列尚未初始化。如果你知道查询将返回多少行,你可以说:

Title = new String[numRows];

但如果不这样做,则需要运行SELECT count(*) ...查询,或者使用ArrayList或其他可调整大小的列表,而不是数组。


您的代码结构也非常糟糕,这也是您在调试时遇到困难的原因之一。我已经在下面清理了你的代码,并评论解释了我的更改:

public class YourClass
{
  private static final int MAX_ID = 8; // or however you want to set the size
  private String[] title; // [] after the type is easier to read, lower case variables
  private Connection conn; // I'm assuming the class will be provided a DB connection
  // Note the Statement and ResultSet objects are not defined in the class, to
  // minimize their scope.
  public void queryInfo() // name suggests a query (potentially expensive) will be run
  {
    title = new String[MAX_ID]; // **initialize title**
    // We use a try-with-resources block to ensure the statement is safely closed
    // even better would be to use a PreparedStatement here
    try(Statement st = conn.statement())
    {
      // You're executing 8 separate queries here, where one will do
      String query = "SELECT * FROM students WHERE ID >= 1 AND ID <= "+MAX_ID;
      // Again, we need to close the result set when we're done
      try(ResultSet rs = st.executeQuery(query))
      {
        int i = 0;
        while (rs.next())
        {   
          title[i++] = rs.getString("StudentName");
        }
      } // close our ResultSet
    } // close our Statement
  }
  // provide a separate getter method, rather than making the array public
  public String[] getTitles()
  {
    return title;
  }
}

还有更多需要改进的地方——使用数组似乎是一个糟糕的设计,调用一个填充类变量的方法也是如此,而不是简单地让queryInfo()返回一个新数组。您也可以研究使用PreparedStatement。希望这些建议能有所帮助。

确保Title数组和Statement St对象为且不为null。这是我唯一怀疑的两个原因。如果不起作用,请给予完全堆叠。

Title数组为NULL。"new"此数组的大小等于行数。如果您不知道行数,请激发一个count(*) query first,找出行数,然后输入Title数组,或者使用ArrayList<String>而不是String数组。

我假设您尚未初始化Title数组,您必须将其设置为某个值,否则它将为null,这将导致nullPointerException,但正如其他人所说,无法确定,因为您没有给我们完整的堆栈跟踪,甚至没有给我们异常的行号。在这种情况下,应该这样处理异常:

try{
    //your code here
}catch(Exception ex){
    ex.printStackTrace();
}

这段代码将为您提供完整的堆栈跟踪,使您更容易跟踪问题。此外,您可能需要考虑使用ArrayList而不是数组:

List<String> Title = new ArrayList<String>();

然后添加:

Title.add(Rs.getString("StudentName"));

如果你以后需要它作为一个数组,那么:

String[] title = Title.toArray(new String[Title.size()]);

你可以在这里阅读更多关于ArrayLists的信息。

最新更新