java使用ResultSet从数据库返回字符串值,但方法跳过了“Try”子句?
为什么我的代码是:
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”子句,而只是在最后返回空的“”结果
我的SQL语句:
String SQL = "SELECT lastName FROM customers WHERE firstName=\"Bob\";";
在我的客户表中,我确实有一个“Bob”(他的姓是“Mike”)的条目
我的客户表:
姓/名/地址/电子邮件
编辑
如果我将返回类型更改为“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();
}
}
# 1 楼答案
根据您上次的编辑,我猜您的记录比一个多
所以把你的代码改成
而且,您的代码不会跳过
try
块