我如何将参数值传递给MySql存储过程

时间:2011-12-21 09:49:32

标签: mysql swing

我为更新查询创建了MySQL存储过程。

delimiter //
create procedure studentrcs(sname varchar(20),smark1 int(3),smark2 int(3),stotal int(10),inout Regno int(6))
begin
UPDATE studentrecords set student_name=sname,mark1=smark1,mark2=smark2,total=stotal where Reg_no=Regno;
end;//

之后,通过可调用语句如何将值(在运行时)作为参数传递

CallableStatement calstat=null;    
calstat=conn.prepareCall("{call studentrcs(?,?,?,?,?)}"); // **how i can pass the value here(at run time).**
             //System.out.println("Update");
                    calstat.setString(1,tname.getText());
                    calstat.setString(2, treg.getText());
                    calstat.setString(3, tmark1.getText());
                    calstat.setString(4, tmark2.getText());
                    calstat.setString(5, ttotal.getText());

                    calstat.executeUpdate();

1 个答案:

答案 0 :(得分:0)

您的存储过程中指定了INOUT参数(Regno),因此您需要为其输入指定值并使用CallableStatement.registerOutParameter方法进行注册。另外,请尝试为int输入参数设置int值。

例如:

CallableStatement calstat=null;    
calstat=conn.prepareCall("{call studentrcs(?,?,?,?,?)}"); // **how i can pass the value here(at run time).**
//System.out.println("Update");
  calstat.setString(1,tname.getText());
  calstat.setInt(2, Integer.parseInt(treg.getText()));
  calstat.setInt(3, Integer.parseInt(tmark1.getText()));
  calstat.setInt(4, Integer.parseInt(tmark2.getText()));
  calstat.setInt(5, Integer.parseInt(ttotal.getText()));

  calstat.registerOutParameter(5, Types.NUMERIC);

  calstat.executeUpdate();

我假设所有这些都在try catch finally块中,所以如果NumberFormatExceptiontmark1.getText(),{tname.getText() { {1}}或tmark2.getText()返回无效的整数值。

有关从Java here

调用MySQL例程的更多信息

顺便说一句,我不知道为什么你不只是将SQL更新方法转储到它自己的Java方法中并调用它而不是创建存储的MySQL例程。只是我的意见!