Oracle JDBC and Oracle CHAR data type

后端 未结 5 1963
别跟我提以往
别跟我提以往 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:30

    If you want

    stmt.setString(1, "a");    // This won't return any records
    

    to return a record, try

    conn.prepareStatement("select * from x where c = cast(? as char(4))")
    
    0 讨论(0)
  • 2020-11-29 12:44

    I have nice fix for this. You have to add one property while getting connection from database.

    NLS_LANG=american_america.AL32UTF8
    

    or in Java connection you can use below code:

    java.util.Properties info = new java.util.Properties();
    info.put ("user", user);
    info.put ("password",password);
    info.put("fixedString","TRUE");
    info.put("NLS_LANG","american_america.AL32UTF8");
    info.put("SetBigStringTryClob","TRUE");
    String url="jdbc:oracle:thin:@"+serverName;
    log.debug("url="+url);
    log.debug("info="+info);
    Class.forName("oracle.jdbc.OracleDriver");
    conn  = DriverManager.getConnection(url,info);
    
    0 讨论(0)
  • 2020-11-29 12:48

    I don't see any reason to use CHAR datatype even if it is char(1) in Oracle. Can you change the datatype instead?

    0 讨论(0)
  • 2020-11-29 12:48

    the other way is modify your sql as

    select * from x where NVL(TRIM(c),' ') = NVL(TRIM('a'),' ')
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题