如何调用JDBC参数化存储过程

问题描述 投票:0回答:2

我需要从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参数

java sql-server stored-procedures jdbc
2个回答
1
投票

有一对夫妇与您的代码的问题。

首先,不要使用JDBC ODBC驱动程序!它是不稳定的,并且可能无法正常工作。使用微软的own jdbc driver,或者甚至更好,使用jTDS,这是SQL Server的优秀的开源JDBC驱动程序。

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

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
投票

尝试这个

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
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.