终于学到存储过程了,谁能给我来个C#版的调用存储过程的例子(也包括SQL写的存储过程)
1.要经典的,思路清晰的,全面的(包括往存储过程里传参数,和返回参数)
2.为了不太麻烦高手,先写了一部分,但流程不清楚(比如整体流程改怎么写,我找的网上例子不关闭SqlConnection,改关闭SqlCommand了,为什么?)
3.请高手自行添加.对了,把try,catch也加里边,我写的一直不规范
4.不要用SqlDataReader了,这个我已经会了,把SqlDataAdapter和DataSet配合的经典例子也加进去我的代码中去
5.这些问题都是菜鸟经常问到的问题,希望高手多帮助菜鸟,详细解答,十分感激!
asp.net程序部分
-------------------------------------
string strCon = ConfigurationManager.ConnectionStrings[ "ConnectionStr1 "].ConnectionString;
SqlConnection conn = new SqlConnection(strCon);
SqlCommand cmd = new SqlCommand( "StoredProcedure_Test1 ", conn);//存储过程名
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.Add();
cmd.Connection.Open();
SqlDataReader reader = cmd.ExecuteNonQuery();
cmd.Connection.Close();
sql server部分
-------------------------------------
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName>
-- Add the parameters for the stored procedure here
<@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0> ,
<@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0>
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT <@Param1, sysname, @p1> , <@Param2, sysname, @p2>
END
GO
------解决方案--------------------#region 保存法律法规导数据库
/// <summary>
/// 保存法律法规导数据库
/// </summary>
/// <returns> 保存成功,返回1;保存失败,返回0 </returns>
private int SavePolicyToDataBase()
{
int result = 0;
if (ulPolicy.HasFile && !IfFileTypeValid())
{
ShowMessageBox( "您只能上传类型为“mht”的文件 ");
return 0;
}
string strCommand = "PolicyManageEdit ";
DbCommand cmd = db.GetStoredProcCommand(strCommand);
db.AddInParameter(cmd, "@ID ", DbType.String, ViewState[ "ID "].ToString());
db.AddInParameter(cmd, "@PolicyName ", DbType.String, txtTopic.Text.Trim());
if (ulPolicy.HasFile) //如果用户选择了新的文件,则上传新的文件(UpLoadPolicy函数会返回服务器端路径)
{
db.AddInParameter(cmd, "@FullPath ", DbType.String, UpLoadPolicy().Trim());
}
else //如果用户没有选择新的文件,原有的文件路径已经在页面中的超级链接中保存了,只要照单全收
{
db.AddInParameter(cmd, "@FullPath ", DbType.String, lbFile.NavigateUrl.Trim());
}