JDBC调用存储过程

一. JDBC调用存储过程

(1)使用存储过程SQL编写的程序代码,等一段语句和控制流语句。在创建时被编译成机器代码和存储在数据库中的client转让。

存储过程具有以下优势: 

1.所生成的机器代码被永久存储在数据库中,client调用时不须要又一次编译,运行起来效率要高一些。 

2.存储过程的网络使用效率比等效的SQL 语句要高。

(2)JDBC通过java.sql.CallableStatement接口调用数据库server中的存储过程;

(3)CallableStatement接口继承了PreparedStatement,PreparedStatement中经常使用的方法也适用于CallableStatement接口,

接口中经常使用的方法有:

 1.public void setString(int n,String x)  throws SQLException

将一个字符串类型的数据值x写入存储过程调用命令的第n个“?”号处,取代“?”,n为预编译语句中“?”的序号,第一个“?”的序号为1。

 2.public ResultSet executeQuery() throws SQLException     

运行一个会返回ResultSet结果集的存储过程。

 3.public boolean execute() throws SQLException
通用的存储过程运行方法

4.public void registerOutParameter(int n,int sqlType)  throws SQLException
将存储过程调用命令{call …}中第n个位置处的“?

”參数注冊声明为输出(OUT)參数。并定义返回数据的类型。返回数据类型SqlType能够用java.sql.Types类中的符号常量表达。

5.public int getInt(int n) throws SQLException
读取存储过程调用命令中“?”位置处的一个整数返回值,n为“?”号在存储过程调用命令中的序号。


二.实例讲解

(1).调用一个可以返回一个ResulSet结果集的存储过程。对titles表的书名字段进行模糊查询,返回书名、类型、单位价格数据。操作过程例如以下: 

第1步:在pubs中创建一个名为exam4的存储过程完毕查询。(在数据库中SQL Server中完毕)

use pubs
go
create proc  exam4 @key varchar(50)
as
begin
   select title,type,price from titles  where title like @key
end
第2步:新建一个名为exam608.jsp的页面,在此JSP网页中调用此存储过程。 

<%@ page contentType="text/html; charset=gb2312" language="java"
	import="java.sql.*" errorPage=""%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
	<%
		Connection con = null;
		CallableStatement st = null;
		ResultSet rs = null;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			String url = "jdbc:sqlserver://localhost:1433;databaseName=pubs;user=sa;password=";
			con = DriverManager.getConnection(url);

			String sql = "{call exam4(?)}"; //效果往这来看!!!
			st = con.prepareCall(sql);
			st.setString(1, "%the%");

			rs = st.executeQuery();
			while (rs.next()) {
				out.print(rs.getString(1));
				out.print(rs.getString(2));
				out.print(rs.getString(3));
				out.print("<br>");
			}

		} catch (Exception e) {
			out.print("数据库操作出错:" + e);
		} finally {
			if (rs != null)
				rs.close();
			if (st != null)
				st.close();
			if (con != null)
				con.close();
		}
	%>
</body>
</html>


(2)调用一个存储过程,给titles表加入一条新记录,新记录中至少包括书号、书名、类型、单位价格、出版日期五个数据。用存储过程实现。

操作过程例如以下: 

第1步:在pubs中创建一个名为newRecord的存储过程,输入下面代码:

use pubs
go
create proc  newRecord @title_id varchar(50),
                       @title varchar(100),
                       @type varchar(30),
                       @price money,
                       @pubdate datetime
as
begin
  insert into titles(title_id,title,type,price,pubdate)
      values(@title_id,@title,@type,@price,@pubdate) 
end 

第2步:建立一个名为exam609.jsp的JSP表单页面供用户输入图书信息。

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="exam610.jsp">
  请输入书号(如AD3344):
  <label>
  <input name="book_id" type="text" id="book_id" />
  </label>
  <p>请输入书名(如Java程序设计):
    <label>
    <input name="book_name" type="text" id="book_name" />
    </label>
  </p>
  <p>请选择书的类型:
    <label>
    <select name="book_type" id="book_type">
      <option value="business">business</option>
      <option value="psychology">psychology</option>
      <option value="trad_cook">trad_cook</option>
      <option value="popular_comp">popular_comp</option>
    </select>
    </label>
  </p>
  <p>请输入书的单位价格(如45.3):
    <label>
    <input name="book_price" type="text" id="book_price" />
    </label>
  </p>
  <p>请输入图书的出版日期(如2004-3-6):
    <label>
    <input name="pub_date" type="text" id="pub_date" />
    </label>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="提交" />
    </label>
  </p>
</form>
</body>
</html>


第3步:定义exam610.jsp读取表单中的数据并写入数据库中。 

<%@ page contentType="text/html; charset=gb2312" language="java" import="java.sql.*"  errorPage="" %>
<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>无标题文档</title>
</head>

<body>
<%
   String book_id=request.getParameter("book_id");
   String book_name=request.getParameter("book_name");
   String book_type=request.getParameter("book_type");
   String book_price=request.getParameter("book_price");
   String pub_date=request.getParameter("pub_date"); 
   	Connection	         con=null;
   CallableStatement     st =null;
	try
	{
      Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
	  String url="jdbc:sqlserver://localhost:1433;databaseName=pubs;user=sa;password=";
	  con = DriverManager.getConnection(url);   
	  String sql="{call newRecord(?,?,?,?,?

)}"; st=con.prepareCall(sql); st.setString(1,book_id); st.setString(2,book_name); st.setString(3,book_type); st.setDouble(4,Double.parseDouble(book_price)); st.setString(5,pub_date); st.execute(); out.println("成功增加记录,请用查询分析器验证"); } catch(Exception e) { out.println(e); } finally { if(st != null ) {st.close();} if(con != null ) {con.close();} } %> </body> </html>








版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/blfshiye/p/4804211.html