使用 ResultSet 从数据库获取 return 字符串值,但方法会跳过 "Try" 子句?

Using ResultSet to return string value from database but method skips the "Try" clause?

为什么我的代码如下:

PrintWriter pw = response.getWriter();
pw.println(getValueOf(SQL, "lastName");

将其传递到我的方法后不打印任何内容:

public static String getValueOf(String sql, String colName)
{
   String result = "";

   try
   {
       Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
       PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
       ResultSet rs = pst.executeQuery();

       while (rs.next())
            result = rs.getString(colName);

       conn.close();

       return result;
   }
   catch (Exception e)
   {
       e.printStackTrace();
   }

   return result;
}

换句话说,为什么它似乎完全跳过 "try" 子句而只是跳到 return 最后的空 "" 结果?

我的SQL声明:

String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";

我的客户 table.

中确实有一个人 "Bob"(他的姓是 "Mike")的条目

我的客户Table:

姓氏/名字/地址/电子邮件

编辑

如果我将 return 类型更改为 "void" 它可以正常工作,但我实际上需要一个字符串值。

备用代码:

 public static void getValueOf(String sql, String colName, PrintWriter pw)
    {

       try
       {
           Connection conn = (Connection) accessDB.connecttoDB(); // pre-defined funct in my other class that works
           PreparedStatement pst = (PreparedStatement) conn.prepareStatement(sql);
           ResultSet rs = pst.executeQuery();

           while (rs.next())
                pw.println(rs.getString(colName)); // This does print out to the webpage as "Mike"

           conn.close();


       }
       catch (Exception e)
       {
           e.printStackTrace();
       }
    }

根据您上次的编辑,我猜您的记录 一条 条多

所以将您的代码更改为

 if (rs.next()) {
        result = rs.getString(colName);
 }

而且,您的代码不会跳过 try