Oracle JDBC and Oracle CHAR data type

后端 未结 5 1981
别跟我提以往
别跟我提以往 2020-11-29 12:03

I have a tricky issue with the Oracle JDBC driver\'s handling of CHAR data types. Let\'s take this simple table:



        
5条回答
  •  无人及你
    2020-11-29 12:54

    Gary's solution works well. Here's an alternative.

    If you are using an Oracle JDBC driver, the call to prepareStatement() will actually return an OraclePreparedStatement, which has a setFixedCHAR() method that automatically pads your inputs with whitespace.

    String sql = "select * from x where c = ?";
    OraclePreparedStatement stmt = (OraclePreparedStatement) conn.prepareStatement(sql);
    stmt.setFixedCHAR(1, "a");
    ...
    

    Obviously, the cast is only safe if you are using the Oracle driver.

    The only reason I would suggest that you use this over Gary's answer is that you can change your column sizes without having to modify your JDBC code. The driver pads the correct number of spaces without the developer needing to know/manage the column size.

提交回复
热议问题