JDBC查询返回没有行,但是交互式查询呢?

时间:2009-11-03 21:46:29

标签: java jdbc

我正在尝试从SolarWinds网络性能数据库(MS SQL 2005)中检索数据,并且交互式工作的查询(在Orion数据库管理器中)在通过JDBC运行时不返回任何行。有什么想法吗?

查询本身是一个令人震惊的(我不喜欢MS-SQL日期/时间处理,我相信强制这样的查询按日期/小时加入)。我可以通过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,然后查询工作。

2 个答案:

答案 0 :(得分:1)

对于您的查询,日期/时间戳将使用PreparedStatement#setDate()/setTimestamp()进行设置。不仅要避免SQL注入,还要防止格式化字符串表示形式中的错误。

答案 1 :(得分:1)

JDBC语法不会使用分号终止SQL语句。

将最后一个子句添加到SQL字符串的行应为:

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