因此,对于一个学校项目,我正在构建一个不和谐的机器人。我内置的功能之一是,他可以从MySQL数据库检索gif链接,并将其发送给消息。现在,我的问题是我只能从数据库中检索一条记录,而没有其他记录。如果将我使用的查询放入MySQL工作台并运行它,它将检索这些记录。
这是检索gif的方法
public static ArrayList<Gif> GetGifsFromDB(String msg){
ArrayList<Gif> gifs = new ArrayList<>();
try(Connection conn = (Connection)DriverManager.getConnection(url, userName, password)){
Class.forName("com.mysql.jdbc.Driver").newInstance();
Statement stmnt = conn.createStatement();
String sql = "Select * from gif WHERE Type = '" + msg + "'";
stmnt.execute(sql);
try(ResultSet rs = stmnt.getResultSet()){
while(rs.next()){
Gif g = new Gif();
g.setID(rs.getInt("GifID"));
g.setURL(rs.getString("GifURL"));
System.out.println(g.getID() + g.getURL());
gifs.add(g);
}
rs.close();
conn.close();
}
}
catch(SQLException ex){
System.err.println(ex.getMessage());
}
catch(Exception ex){
System.err.println(ex.getMessage());
}
return gifs;
}
数据库中的“类型”只是一个类别。根据我拥有的测试数据,这3种类型都不是,令人惊讶且孤独。只有no会返回gif。
最佳答案
删除结束的ResultSet和Connection行:
rs.close();
conn.close();
您已经在使用try-with-resources关闭它