jdbc查询不返回行,但交互式查询返回行?

fhity93d  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(368)

我试图从solarwinds网络性能数据库(mssql2005)中检索数据,而一个交互工作非常好的查询(在orion数据库管理器中)在通过jdbc运行时不返回任何行。有什么想法吗?
查询本身是一个令人震惊的问题(我不喜欢mssqldate/time处理,我相信它会强制按日期/小时对连接进行这样的查询)。我可以通过println剪切和粘贴查询输出,它工作正常,但在我的程序中它不返回任何行(但不会抛出任何异常)。
我假设查询复杂性无关紧要,因为jdbc不会尝试解析查询—它只会将查询传递到后端。

String qtext = new String("select rd.nodeid, rd.hr, rd.response, rd.loss, cd.cpu, cd.mem, bd.nomem, bd.smmiss, bd.mdmiss, bd.bgmiss, bd.lgmiss, bd.hgmiss" + " from" +
    " (select nodeid,  DATEPART(hh, DateTime) as hr, round(avg(AvgResponseTime), 0) as response, round(avg(PercentLoss), 0) as loss" +
    "    from ResponseTime_Detail" +
    "    where DateTime >= " + today + " and DateTime < " + tomorrow +
    "    group by nodeid, DATEPART(hh, DateTime)" +
    " ) as rd" +
    " left outer join" +
    " (select nodeid,  DATEPART(hh, DateTime) as hr, round(avg(AvgLoad), 0) as cpu, bound(avg(AvgPercentMemoryUsed), 0) as mem" +
    "      from CPULoad_Detail" +
    "    where DateTime >= " + today + " and DateTime < " + tomorrow  +
    "      group by nodeid, DATEPART(hh, DateTime)" +
    " ) as cd" +
    " on rd.nodeid = cd.nodeid and rd.hr = cd.hr" +
    " left outer join" +
    "  (select nodeid,  DATEPART(hh, DateTime) as hr, round(avg(BufferNoMem), 0) as nomem, round(avg(BufferSmMiss), 0) as smmiss, round(avg(BufferSmMiss), 0) as mdmiss," +
    "          round(avg(BufferBgMiss), 0) as bgmiss, round(avg(BufferLgMiss), 0) as lgmiss, round(avg(BufferHgMiss), 0) as hgmiss" +
    "      from CiscoBuffers_Detail" +
    "    where DateTime >= " + today + " and DateTime < " + tomorrow +
    "      group by nodeid, DATEPART(hh, DateTime)" +
    " ) as bd" +
    " on rd.nodeid = bd.nodeid and rd.hr = bd.hr" +
    " order by rd.nodeid, rd.hr;");
 System.out.println("Query from hell = [" + qtext + "]");
 st = sol.db.createStatement();
 System.out.println("Created statement");
 rs = st.executeQuery(qtext);
 System.out.println("Executed statement");
 while (rs.next()) {
   ....
 }

谢谢大家的建议。我认为问题在于日期/时间的解释。我按照建议使用了preparedstatement,然后查询就成功了。

uhry853o

uhry853o1#

至于您的查询,日期/时间戳将使用 PreparedStatement#setDate()/setTimestamp() . 不仅可以避免sql注入,还可以防止在日期的字符串表示中出现格式错误。

snvhrwxg

snvhrwxg2#

jdbc语法不会用分号终止sql语句。
将最后一个子句添加到sql字符串的行应为:

" order by rd.nodeid, rd.hr");

相关问题