最近做了个Java的小项目(第一次写Java的项目哦), 到网上搜索了半天,找到了一个比较好点的调用存储过程的例子,而且网上普遍采用的都是setXXX((int parameterIndex, XXX x)的形式。这种形式感觉不是很直观,下面就发布一个完整的采用setXXX(String parameterName, XXX x)的编写方法。创建数据表,存储过程的代码都完整发布。
创建表:
CREATE TABLE [BookUser] (
[UserID] [int] IDENTITY (1, 1) NOT NULL ,
[UserName] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Title] [nvarchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Guid] [uniqueidentifier] NOT NULL CONSTRAINT [DF_BookUser_Guid] DEFAULT (newid()),
[BirthDate] [datetime] NOT NULL ,
[Description] [ntext] COLLATE Chinese_PRC_CI_AS NOT NULL ,
[Photo] [image] NULL ,
[Other] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL CONSTRAINT
[DF_BookUser_Other] DEFAULT ('默认值'),
CONSTRAINT [PK_BookUser] PRIMARY KEY CLUSTERED
(
[UserID]
) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
创建存储过程:
CREATE PROCEDURE InsertUser
@UserName varchar(50),
@Title varchar(255),
@Guid uniqueidentifier,
@BirthDate DateTime,
@Description ntext,
@Photo image,
@Other nvarchar(50),
@UserID int output
As
Set NOCOUNT ON
If Exists (select UserID from BookUser Where UserName = @UserName)
RETURN 0
ELSE
Begin
INSERT INTO BookUser (UserName,Title,Guid,BirthDate,Description,Photo,Other) VALUES(@UserName,@Title,@Guid,@BirthDate,@Description,@Photo,@Other)
SET @UserID = @@IDENTITY
RETURN 1
End
GO
JSP代码:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import = "java.sql.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/uploadfile/201210/16/47102646745.gif";
java.io.FileInputStream f = new java.io.FileInputStream(FilePath);
Date rightNow = Date.valueOf("2007-9-9");
cmd.setString("UserName","mengxianhui"); //注意修改这里,存储过程验证了UserName的唯一性