简体   繁体   中英

How to set a JDBC PreparedStatement parameter for an Oracle CHAR field?

I think I am missing something obvious with my Oracle JDBC prepared statement. I am trying to create a PreparedStatement that selects column A from TABLE where B is the parameter. For example, this is what I've boiled down the test code too:

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"));

Now this doesn't work, I currently get java.sql.SQLException: Result set after last row because of the ResultSet being empty.

However, this works:

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"));

Notice how I hard coded the WHERE statement with a string.

Anything obvious I am missing?

My maven dependency is defined as:

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

Column B is defined as a CHAR(50)

Here is some debug information from 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;

With output

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

因为您的字段的定义是CHAR(50) ,所以我认为您应该用空格填充String

除了@LppEdd答案,您还可以通过以下方式设置参数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM