2016-04-29 60 views
0

請幫我解決一個問題。我需要打印一個用戶的名字,但只能得到它的第一個字母。JDBC CallableStatement問題

public static void main(String[] args) {    
    Connection conn = null; 
    java.sql.CallableStatement stmt = null;  

     try { 
      Class.forName(JDBC_DRIVER); 
      conn = DriverManager.getConnection(DB_URL,USER,PASS);  

      String sql = "{call retrieveFirstName(?,?)}"; 
      stmt = conn.prepareCall(sql); 

      //Bind IN parameter first, then bind OUT parameter 
      int uID = 1; 
      ((java.sql.CallableStatement)stmt).setInt(1,uID); 
      ((java.sql.CallableStatement)stmt).registerOutParameter(2, java.sql.Types.VARCHAR); 

      ((java.sql.CallableStatement)stmt).execute(); 

       //Retrieve employee name with getXXX method 
      String userName = ((java.sql.CallableStatement)stmt).getNString(2); 
      System.out.println("User Name with ID:" + uID + " is " + userName);   

     } catch (ClassNotFoundException | SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     finally { 
      //close resources 
     } 
} 

這裏是一個過程

create procedure retrieveFirstName 
@userID int, 
@firstName varchar(250) output 
as 
begin 
select @firstName=first_name 
from user_account 
where [email protected] 
end 
+0

你的java代碼似乎很好。我認爲問題在於你的存儲過程。你可以使用Sql客戶端來確認過程的輸出嗎? –

回答

0

您指定的輸出參數爲

((java.sql.CallableStatement)stmt).registerOutParameter(2, java.sql.Types.VARCHAR); 

不指定VARCHAR的精度。

請嘗試指定精度作爲registerOutParameter的第三個參數。