Java JDBC Postgres:选择单引号

时间:2014-12-03 08:00:45

标签: java postgresql jdbc prepared-statement

我一直在测试代码,发现问题是单引号。正如您在下面的查询中看到的,我使用了where子句中的单引号。如果我删除,我得到一个结果,但如果我把它放回去,即使是满足过滤器的行,它不返回任何东西。我也尝试过使用这个视图。将where子句放在视图中并直接选择视图而不使用任何过滤器。它仍然没有返回任何东西。

  try {
    Class.forName("org.postgresql.Driver").newInstance();
    Connection Conn = DriverManager.getConnection("jdbc:postgresql://{ipaddress}/database?user=postgres&password=password");

    Statement Stmt = Conn.createStatement();
    String sqlCommand = "SELECT col1_timestamp , col2 FROM table WHERE col1_timestamp > '00:01:00' ";

    ResultSet RS = Stmt.executeQuery(sqlCommand);

    while (RS.next()) {
        data.add(RS.getInt("col1_timestamp ")
                + "=>" + RS.getString("col2"));
    }
    // Clean up after ourselves
    RS.close();
    Stmt.close();
    Conn.close();
}
catch (SQLException E) {
    System.out.println("SQLException: " + E.getMessage());
    System.out.println("SQLState:     " + E.getSQLState());
    System.out.println("VendorError:  " + E.getErrorCode());
}
catch(Exception ex)
{
    System.out.println(ex.getMessage());
}

我也试过了:

  String sqlCommand = "SELECT col1_timestamp, col2 FROM table "
                + " WHERE col2= ? AND (now() - col1_timestamp::timestamp with time zone) < interval ? ";

        PreparedStatement preparedStatement = Conn.prepareStatement(sqlCommand);
        preparedStatement.setString(1, "test");
        preparedStatement.setTime(2, new Time(new Long(-28680000))); //String(2, "00:02:00");

仍然不起作用,而是在第二个参数上抛出错误。

这是非常简单的任务,但它总是返回一个空白值。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

区间文字非常有限(在一般的SQL和Postgres中),你不能使用参数作为区间文字的单位

如果你总是拥有相同的单位(例如几分钟),你可以这样做:

String sqlCommand =
   "SELECT col1_timestamp, col2 FROM table " + 
   " WHERE col2= ? " + 
   " AND (now() - col1_timestamp::timestamp with time zone) < interval '1' minute * ?";

PreparedStatement preparedStatement = Conn.prepareStatement(sqlCommand);
preparedStatement.setString(1, "test");
preparedStatement.setInt(2, 5); // five minutes

如果您需要查询不同的单位(小时,分钟,天),则需要为每个单位使用适当的分钟数,或者每次更改SQL:interval '1' day * ?或{{1} }