如何为Oracle CHAR字段设置JDBC PreparedStatement参数?

时间:2017-03-22 11:28:20

标签: java oracle jdbc

我认为我遗漏了一些明显的Oracle JDBC预编译语句。我正在尝试创建PreparedStatement,从A中选择列TABLE,其中B是参数。例如,这也是我将测试代码归结为:

Class.forName("oracle.jdbc.driver.OracleDriver");
final Connection connection = DriverManager.getConnection(<Oralce JDBC connection stuff>);
final PreparedStatement findStatement = connection.prepareStatement("SELECT A FROM TABLE WHERE B = ?");

findStatement.setString(1, "TEST");

final ResultSet results = findStatement.executeQuery();
results.next();

System.out.println(results.getString("A"));

现在这不起作用,因为java.sql.SQLException: Result set after last row为空,我目前得到ResultSet

然而,这有效:

Class.forName("oracle.jdbc.driver.OracleDriver");
final Connection connection = DriverManager.getConnection(<Oralce JDBC connection stuff>);
final PreparedStatement findStatement = connection.prepareStatement("SELECT A FROM TABLE WHERE B = 'TEST'");

final ResultSet results = findStatement.executeQuery();
results.next();

System.out.println(results.getString("A"));

注意我是如何使用字符串对WHERE语句进行硬编码的。

我遗失了哪些明显的东西?

我的maven依赖关系被定义为:

<dependency>
  <groupId>com.oracle.jdbc</groupId>
  <artifactId>ojdbc7</artifactId>
  <version>12.1.0.2</version>
 </dependency>

B定义为CHAR(50)

以下是Oracle的一些调试信息

select
  s.sql_text,
  bc.position,
  bc.value_string
from v$sql s
  left join v$sql_bind_capture bc
  on bc.sql_id = s.sql_id
  and bc.child_number = s.child_number
where
  s.sql_text like 'SELECT A%'
order by s.sql_id, bc.position;

带输出

SQL_TEXT                             | Position                       | Value_String
SELECT A FROM TABLE WHERE B = :1     | 1                              | TEST
SELECT A FROM TABLE WHERE B = 'TEST' | <null>                         | <null>

2 个答案:

答案 0 :(得分:2)

由于您的字段定义为CHAR(50),我认为您应该用空格填充String

答案 1 :(得分:2)

除了@LppEdd答案,你也可以这样设置参数:

((OraclePreparedStatement)findStatement).setFixedCHAR(1, "TEST");