我创建了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
答案 0 :(得分:2)
但我收到的错误是“程序或功能”AddContactInfo'需要参数'@returnval',这是未提供的。“
您必须将new SqlParameter("@returnval", SqlDbType.Int)
设置为output
参数:
foreach (SqlParameter obj in param)
{
if (cmd.ParameterName == "@returnval")
{
cmd.Direction = ParameterDirection.Output
}
cmd.Parameters.Add(obj);
}
当然,这要求所有SP在适当时具有相同的@returnval
。在创建参数列表时最好设置它。