从Java错误调用Sql Server

时间:2017-05-31 01:23:35

标签: java sql-server

我在Java类中有以下代码:

CallableStatement stmt = con.prepareCall({ call myInsert( ?, ?, ?)});
stmt.setString(1, myTO.getField1());
stmt.setString(2, myTO.getField2());
stmt.setString(3, myTO.getField3());
stmt.executeUpdate();

数据库中的myInsert定义为:

IF OBJECT_ID ( 'myInsert', 'P' ) IS NOT NULL   
DROP PROCEDURE myInsert;  

GO 

CREATE PROCEDURE [myInsert]
@Field1 as uniqueidentifier,
@Field2 as varchar(120),
@Field3 as varchar(120)
@myId UNIQUEIDENTIFIER OUTPUT

AS

SET @myId = NEWID()

INSERT INTO myTable
     (myID, Field1, Field2, Field3) 
    VALUES ( @myID, @Field1, @Field2, @Field3 )

但是,调用失败并出现以下错误:

com.microsoft.sqlserver.jdbc.SQLServerException: Procedure or function 'myInsert' expects parameter '@myId', which was not supplied.
    at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:232)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1672)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:460)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:405)
    at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7535)
    at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2438)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:208)
    at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:183)
    at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:348)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:98)
    at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:98)

我做错了什么?我该如何解决这个问题?

感谢阅读!

1 个答案:

答案 0 :(得分:0)

我认为你错过了你的参数。

CallableStatement stmt = con.prepareCall("{ call myInsert(?, ?, ?, ?)}");
stmt.setString(1, myTO.getField1());
stmt.setString(2, myTO.getField2());
stmt.setString(3, myTO.getField3());
stmt.registerOutParameter(4, java.sql.Types.VARCHAR);
stmt.executeUpdate();
System.out.println(stmt.getString(4)); // <-- print @myId