如果您只想设置一些参数,使用JDBC调用存储过程的最佳方法是什么?
如果我只是使用SQL,我可以在SQL中按名称设置参数,以调用sproc。例如。如果我有一个包含9个参数的存储过程并且我想设置参数1,2和9,剩下的就是默认值,我可以运行这个SQL:
exec my_stored_procedure
@parameter_1 = "ONE",
@parameter_2 = "TWO",
@parameter_9 = "NINE"
使用JDBC(特别是jConnect 6.0),似乎在使用CallableStatement时,您必须按整数索引设置参数,而不是它们的名称。如果我尝试为上面的存储过程创建一个CallableStatement,有9个参数,并且只设置参数1,2和9,如下所示:
myStoredProcedureCall =
sybConn.prepareCall("{call my_stored_procedure (?, ?, ?, ?, ?, ? , ?, ?, ?)}");
myStoredProcedureCall.setString(1, "ONE");
myStoredProcedureCall.setString(2, "TWO");
myStoredProcedureCall.setString(9, "NINE");
ResultSet paramResults = myStoredProcedureCall.executeQuery();
然后我抛出了这个SQLException:
*** SQLException caught ***
SQLState: JZ0SA
Message: JZ0SA: Prepared Statement: Input parameter not set, index: 2.
Vendor: 0
对于我想要做的事情的一些背景知识,我需要创建一个流程来接收来自IBM MQ流的产品信息,然后在第三个应用程序中创建产品。第三方应用程序使用Sybase来存储它的数据,并创建一个产品,我需要调用一个包含大约130个参数的存储过程。对于我需要创建的产品类型,只需要设置其中的大约15个参数,其余参数将保留为默认值。
我考虑的选项是:
当然必须有一种更简单的方法吗?
答案 0 :(得分:6)
JDBC不支持此功能。您必须创建一个SQL字符串并执行:
String sql = "exec my_stored_procedure\n@parameter_1 = ?,\n@parameter_2 = ?,\n@parameter_9 = ?";
PreparedStatement stmt = ...
stmt.setString( 1, "ONE" );
stmt.setString( 2, "TWO" );
stmt.setString( 3, "NINE" );
stmt.execute();
请记住:除了{}
和?
等特殊字符外,JDBC不会尝试理解您发送到数据库的SQL。我曾经写过一个JDBC“数据库”,它接受JavaScript代码片段作为“SQL”:我只是实现了DataSource
,Connection
和ResultSet
,我可以使用JDBC接口查询我的应用程序的内存模型但使用JavaScript作为查询语言。
答案 1 :(得分:0)
您可以尝试在String
中编码null或空白 "{call my_stored_procedure (?, ?, null, null, null, null , null, null, ?)}"
答案 2 :(得分:0)
myStoredProcedureCall.setString(9, "NINE");
in above code index no 9 but it will be 3 because your parameter sequence start from 1 ;
Alhrough you can another sql exception.
I think you should use
myStoredProcedureCall =
sybConn.prepareCall("{call my_stored_procedure (?, ?, null, null, null, null , null, null, ?)}");
myStoredProcedureCall.setString(1, "ONE");
myStoredProcedureCall.setString(2, "TWO");
myStoredProcedureCall.setString(3, "NINE");
ResultSet paramResults = myStoredProcedureCall.executeQuery();
答案 3 :(得分:0)
// abobjects.com
以下对我有用
def getIDGEN(sTableName):
proc = db.prepareCall(“{?= call DB.dbo.usp_IDGEN_string_v6(?,?)}”);
proc.registerOutParameter(3, types.INTEGER)
proc.setString(2, sTableName)
proc.setInt(3, 0)
proc.execute()
li_RI_ID = proc.getInt(3)
print str(li_RI_ID) + " obtained from usp_IDGEN_string_v6"
return li_RI_ID
我的特色是
create proc usp_IDGEN_string_v6 (@tablename varchar(32) , @ID numeric )
as
declare @seq numeric
declare @nextID numeric
select @nextID=IDGEN_ID from DB_IDGEN where IDGEN_TableName = @tablename
select @seq=@nextID + 1 from DB_IDGEN where IDGEN_Table
Name = @tablename
update DB_IDGEN set IDGEN_ID = @seq where IDGEN_TableName = @tablename
select @ID = @seq
return @ID