GO
/****** Object: Table [dbo].[Dept] Script Date: 12/21/2006 21:11:40 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Dept](
[DeptID] [int] IDENTITY(1,1) NOT NULL,
[DeptName] [varchar](50) COLLATE Chinese_PRC_CI_AS NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
GO
/****** Object: Table [dbo].[Users] Script Date: 12/21/2006 21:12:53 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY(1,1) NOT NULL,
[UserName] [varchar](50) COLLATE Chinese_PRC_CI_AS NOT NULL,
[DeptID] [int] NULL
) ON [PRIMARY]
SET ANSI_PADDING OFF
set QUOTED_IDENTIFIER ON
go
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[AddUser]
@UserName VARCHAR(50),
@DeptID INT
AS
DECLARE @RecordCount as int
SET @RecordCount =
(SELECT COUNT(*) FROM Users WHERE UserName = @UserName)
IF @RecordCount < 1
BEGIN
INSERT INTO Users(UserName,DeptID) VALUES(@UserName,@DeptID)
RETURN @@IDENTITY
END
{
conn.ConnectionString = ConfigurationManager.ConnectionStrings["ConnString"].ToString();
}
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
comm.Connection = conn;
comm.CommandType = CommandType.StoredProcedure;
comm.CommandText = strSQL;
{
SqlParameterCollection paras = comm.Parameters;
string[] para = paraNames.Split('|');
string[] value = paraValues.Split('|');
for (int i = 0; i < para.Length; i++)
{
SqlParameter sp = new SqlParameter(para[i], value[i]);
paras.Add(sp);
}
}
return comm.ExecuteNonQuery();
}
{
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
comm.Connection = conn;
comm.CommandType = CommandType.Text;
comm.CommandText = "SELECT DeptID,DeptName FROM Dept";
Hashtable ht = new Hashtable();
while (reader.Read())
{
ht.Add(reader.GetInt32(0), reader.GetString(1));
}
reader.Close();
return ht;
}
}
从ExecuteInsert(string strSQL, string paraNames, string paraValues)方法中,大家可以学习到如何通过带参的存储过程来访问数据库。这里传入的参数是"|"分隔的参数名和参数值的字符串。
{
string paraNames = "@UserName|@DeptID";
string paraValues =tbUserName.Text.Trim()+ "|" + ddlDept.SelectedValue.ToString();
DataAccess.ExecuteInsert("AddUser",paraNames,paraValues);
}