java调用SQL server存储过程

最近做数据库课期末系统开发,用的是java语言平台,要用到存储过程的调用,但是书里面没有讲,所以我就查了百度,最后做出来总结一下(文笔不好 见谅)

不带参数的存储过程调用

不带参数的存储过程是最简单的,但是我感觉一般数据库管理系统里面是基本不怎么用的,因为不带参数的话那数据库的查询语句功能就可以满足了,但是我们还是来看一下不带参数要怎么用java调用。首先用T-SQL语句建立存储过程

create proc student
as
select st_id,st_name 
From st_info

建立一个查询st_info 表内学号以及姓名的存储过程

java调用student存储过程(关键代码)

	try {
	Connection con = null;
   	ResultSet res = null;  
        PreparedStatement statement = null;		 
            Class.forName(cfn);
            con = DriverManager.getConnection(url,"sa","123");
            statement = con.prepareStatement();
            res = statement.executeQuery("{call dbo.student}");//调用student存储过程
            while(res.next()){
                String stid = res.getString("st_id");//获取st_id列的元素         
		String stname=res.getString("st_name");
            }
            
        } catch (Exception a) {
            // TODO: handle exception
            a.printStackTrace();
        }               

带输入参数的存储过程调用

先来看T-SQL语句
create proc clname @stid nchar(10)
as
select c_name,c_no,score
from st_info
where st_id=@stid

带输入参数的存储过程寻找有一个语句对输入sql参数进行转换,这个语句是setInt()或者是setString()方法,具体要看你的输入参数的值是什么格式类型的。
try{
		Connection con = null;
         Class.forName(cfn);
         con = DriverManager.getConnection(url,"sa","12345");
        ResultSet res = null;
PreparedStatement pstmt=con.prepareStatement("{call dbo.clname(?)}");//带一个输入参数占位符为?
pstmt.setString(1,"0603060108");//参数的输入值
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
System.out.println(rs.getString("c_name") + ","+rs.getString("c_no") +","+rs.getString("score"));
}
rs.close();
pstmt.close();
}
catch(Exception e){
e.printStackTrace();
}
这个代码call dbo.clname(?)中,“?”的意思就是我们在sql里面创建存储过程输入参数的位置,有几个输入参数就是几个“?”,那么pstmt.setString(1,0603060108)的意思是存储过程中第一个参数的输入值为"0603060108"。如果存储过程中有两个参数值,那么要写为{call dbo.存储过程名(?,?)};ptstmt.setString(1,"xxxx");ptstmt.steString(2,"xxxx");这种形式





猜你喜欢

转载自blog.csdn.net/AAAAAAAKing/article/details/53458402