gpt4 book ai didi

Java - NULL 结果集

转载 作者:行者123 更新时间:2023-11-29 19:57:22 28 4
gpt4 key购买 nike

我有一个从 MySQL 表中获取数据的函数

public ResultSet getAddressID(String city) throws SQLException{
String q = "SELECT PK_ADDRESS_ID FROM tbl_addresses WHERE city =" + "\""+ city+ "\";";
ResultSet rs = executeSearch(q);
return rs;
}

当我尝试 System.out.println(n.getAddressID("Sheffield")); 时,它返回 null。为什么即使我的表中有数据也会发生这种情况(见图)。

enter image description here

public ResultSet executeSearch(String q){
openConnection();
try{
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(q);
closeConnection();
return resultSet;
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
finally {
closeConnection();
return null;
}
}

最佳答案

问题似乎出在您的executeSearch 方法中; finally block 将始终执行,因此通过在 finally block 中返回 null,您实际上覆盖在 try block 中返回的内容!

这可能是一个替代解决方案;请注意,我在方法末尾返回,而不是在 try-catch-finally block 的任何部分内返回。

/**
* Converts a provided ResultSet into a generic List so that the
* ResultSet can be closed while the data persists.
* Source: http://stackoverflow.com/a/7507225/899126
*/
public List convertResultSetToList(ResultSet rs) throws SQLException
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
List list = new ArrayList(50);

while (rs.next())
{
HashMap row = new HashMap(columns);
for(int i = 1; i <= columns; ++i)
{
row.put(md.getColumnName(i), rs.getObject(i));
}
list.add(row);
}

return list;
}

public List executeSearch(String q)
{
List toReturn;
openConnection();
try {
Statement statement = connection.createStatement();
toReturn = this.convertResultSetToList(statement.executeQuery(q));
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
toReturn = new ArrayList();
}
finally {
closeConnection();
}

return toReturn;
}

关于Java - NULL 结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40637980/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com