如何在jdbc中调用参数化存储过程

时间:2014-05-13 02:03:03

标签: java sql-server stored-procedures jdbc

我需要从sql server调用java jdbc中的参数化存储过程。 存储过程在sql

中是这样的
create proc patientreg
@id int
    as
begin
    select [patient_id],[Psurname], [pFirstname], [pMiddlename], [reg_date], [DOB], [Sex], [Phone_num], [Addr],[Email],[dbo].[fncomputeage](DOB) from [dbo].[Patient_registration] where [patient_id] = @id
end

请注意dbo.fncompute(DOB)是一个功能

在JDBC中调用它:

try{
    String str = "{call patientreg(?)}";
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbcdbc:GeneralHospital");
    cstmt = con.prepareCall(str);
    cstmt.setInt(1, Integer.parseInt(t.getText()));
    cstmt.execute();

    int pid = cstmt.getInt(1);
    String sname = cstmt.getString(2);
    String fname = cstmt.getString(3);
    String mname = cstmt.getString(4);
    String regdate = cstmt.getString(5);
    String dob = cstmt.getString(6);
    String sex = cstmt.getString(7);
    String phonenum = cstmt.getString(8);
    String address = cstmt.getString(9);
    String email = cstmt.getString(10);
    int age = cstmt.getInt(11);

    l1.setText(sname+""+ fname+""+mname);
    l3.setText(Integer.toString(pid));
    l4.setText(regdate);
    l5.setText(dob);
    l6.setText(Integer.toString(age));
    l7.setText(sex);
    l8.setText(phonenum);
    l9.setText(address);
    l10.setText(email);
    cstmt.close();
}
catch(Exception ex)
{
    System.out.println("Error occured");
    System.out.println("Error:"+ex);
}

这样做之后会抛出一个异常:

  

错误:java.sql.SQLException:参数1不是OUTPUT参数

2 个答案:

答案 0 :(得分:1)

您的代码存在一些问题。

首先,不要使用jdbc odbc驱动程序!它不稳定,可能无法正常工作。使用Microsoft的own jdbc driver,或者更好的是,使用jTDS,它是Sql Server的一个优秀的开源jdbc驱动程序。

其次,CallableStatement上的getIntgetString等方法用于从存储过程中检索输出参数。你拥有的是一个普通的结果集。

CallableStatement cstmt = con.prepareCall("{call patientreg(?)}");

// add input parameter
cstmt.setInt(1, someInteger);

// execute and get resultset.
ResultSet rs = cstmt.executeQuery();

// read resultset
while (rs.next()) {
    int pid = rs.getInt(1);
    String sname = rs.getString(2);
    String fname = rs.getString(3);
    // etc.
}

// remember to close statement and connection

答案 1 :(得分:-1)

试试这个

ResultSet rs = null;
PreparedStatement cs=null;
Connection conn=getJNDIConnection();
try {
cs=conn.prepareStatement("exec sp_name ?,?");
cs.setString(1, "val1");
cs.setString(2, "val2");
rs = cs.executeQuery();
ArrayList<YourClass> listYourClass = new ArrayList<YourClass>();
while (rs.next()) {
    YourClassret= new YourClass();
    ret.set1(rs.getString(1));
    ret.set2(rs.getString(2));
    ret.set3(rs.getString(3));
    listaObjectX.add(ret);

}
return listYourClass ;
 } catch (SQLException se) {
    System.out.println("Error "+ se.getMessage());
    se.printStackTrace();

} finally {

    try {

        rs.close();
        cs.close();
      con.close();

    } catch (SQLException ex) {
        //do ex.print
    }
}