当我在Postgres数据库中运行此查询时:
select iid from original where accid=1000 and msg_number=1669;
它总是在Postgres DB中返回一个结果,但是当我在Java中运行它时,它不返回任何结果。
这是original
表:
iid: int4
accid: int4
msg_number: int4
这是我的Java代码:
public String getIID(String msgNr) {
String accid=null;
try {
Statement accidStmt = conn.createStatement();
String accidQuery = "select accid from accounts where name='" + clientname + "'";
ResultSet accidResult = accidStmt.executeQuery(accidQuery);
while (accidResult.next())
accid = accidResult.getString("accid");
accidResult.close();
accidStmt.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
String iid = null;
try {
String iidQuery = "select iid from original where accid=" + accid + " and msg_number=" + msgNr;
// String iidQuery = "select iid from original where accid=" + Integer.parseInt(accid) + " and msg_number=" + Integer.parseInt(msgNr);
// String iidQuery = "select iid from original where accid=1000 and msg_number=1669";
Statement iidStmt = conn.createStatement();
ResultSet iidResult = iidStmt.executeQuery(iidQuery);
while (iidResult.next())
iid = iidResult.getString("iid");
iidResult.close();
iidStmt.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return iid;
}
获取accid
的第一个查询有效。但是获取iid
的第二个查询不起作用,结果总是为0行。正如我的代码所示,我已经尝试将accid
转换为Integer,即使我尝试了一个硬值,但此查询并未返回结果。并且它没有进入catch,因为查询执行成功。所以我不知道出了什么问题。
任何帮助都非常感激。
答案 0 :(得分:0)
var“accid”是String Object
accid = accidResult.getString("accid");
您应该始终使用预准备语句。请参阅下面的更新功能:
public int getIID(String msgNr) {
int accid=0;
try {
Statement accidStmt = conn.createStatement();
String accidQuery = "select accid from accounts where name='" + clientname + "'";
ResultSet accidResult = accidStmt.executeQuery(accidQuery);
while (accidResult.next())
accid = accidResult.getInt("accid");
accidResult.close();
accidStmt.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
int iid = 0;
try {
String iidQuery = "select iid from original where accid=? and msg_number=?";
PreparedStatement pst=conn.prepareStatement(iidQuery);
pst.setInt(1,accid);
pst.setInt(2,Integer.parseInt(msgNr));
ResultSet iidResult=pst.executeQuery();
while (iidResult.next())
iid = iidResult.getInt("iid");
iidResult.close();
iidStmt.close();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return iid;
}