我创建了 DataAccessLayer.cs 文件,它帮助我与数据库建立连接以将记录插入数据库,并且我创建了存储过程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class DataAccessLayer
{
SqlConnection con = new SqlConnection("Connection String");
SqlCommand cmd;
public DataAccessLayer()
{
//
// TODO: Add constructor logic here
//
}
public int ExecuteProcedure(String procname, SqlParameter[]param)
{
cmd = new SqlCommand();
cmd.CommandText = procname;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = con;
foreach (SqlParameter obj in param)
{
cmd.Parameters.Add(obj);
}
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
return i;
}
}
使用存储过程将记录插入数据库的代码
SqlParameter[] param = new SqlParameter[]
{
new SqlParameter("@Name",txtFirstName.Text),
new SqlParameter("@DOB",txtDOB.Text),
new SqlParameter("@Address",txtAddress.Text),
new SqlParameter("@CN",ddlCountry.SelectedValue),
new SqlParameter("@SN",ddlState.SelectedValue),
new SqlParameter("CNN",ddlCity.SelectedValue),
new SqlParameter("@Mobile",txtMobile.Text),
new SqlParameter("@Email",txtEmail.Text),
new SqlParameter("@Pincode",txtPincode.Text),
new SqlParameter("@returnval",SqlDbType.Int)
};
int i = DAL.ExecuteProcedure("AddContactInfo", param);
if (i == 1)
{
lblError.Text = "Sucess";
}
else
{
lblError.Text = "Not Sucess";
}
用于插入记录的存储过程
ALTER proc [dbo].[AddContactInfo]
(
@Name varchar(50),
@DOB datetime,
@Address Varchar(max),
@Mobile varchar(15),
@Email varchar(50),
@CN int,
@SN int,
@CNN int,
@Pincode int,
@returnval int output
)
As
Begin
if exists(select Id from Contact_Info where Email=@Email)
begin
set @returnval=-2;
return @returnval;
end
else
begin
insert into Contact_Info(Name,DOB,Address,CountryName,StateName,CityName,Pincode,Mobile,Email,CreatedOn )
values(@Name,@DOB,@Address,@CN,@SN,@CNN,@Pincode,@Mobile,@Email,GETDATE())
if @@ERROR<>0
begin
set @returnval=-3;
return @returnval;
end
else
begin
set @returnval=1;
return @returnval;
end
end
End