C#中调用存储过程的简单示例

记得以前在数据库实验课上使用过存储过程,但并没有在实际编程中使用过,长期没有使用,也忘了如何创建存储过程了。昨天在网上搜了一下,资料还是比较多。不过,为了以后方便查询,就做了个简单示例。

这里主要是针对两种存储过程,即带参数的和不带参数的存储过程各做一个例子。

好了,开始创建存储过程吧!

一、不带参数的存储过程

1、在SqServer查询分析器中创建一个名为spShowTbNews的存储过程

GO

Create Procedure [dbo].[spShowTbNews]

       AS

         select * from RTO_TbNews

 

2C#后台调用存储过程

 

///<summary>

 

        /// @Author:Lucky Hu

 

        /// @Date:2011-09-10

 

        /// @Title:First Test Procedure Ì过程

 

        ///

 

        ///</summary>

 

        string ConStr = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];

 

        SqlConnection conn;

 

        SqlCommand cmd;

 

        protected void Page_Load(object sender, EventArgs e)

 

        {

 

            if(!IsPostBack)

 

            {

 

                dlbind();

 

            }

 

        }

 

 

 

        public void dlbind()

 

        {

 

            conn = new SqlConnection(ConStr);

 

            DataSet myds = new DataSet();

 

            cmd = new SqlCommand("spShowTbNews", conn);//spShowTbNews

 

            cmd.CommandType = CommandType.StoredProcedure;//选择Command对象类型为存储过程

 

            SqlDataAdapter sdp = new SqlDataAdapter();

 

            sdp.SelectCommand = cmd;

 

            sdp.Fill(myds);

 

            ClassList.DataSource = myds;

 

            ClassList.DataBind();

        }

 

 

 效果如下:

 

二、带参数的存储过程

1 创建一个带参数的存储过程

GO

Create Procedure [dbo].[SpShowCommen]

        @Did int

       AS

         select * from RTO_Commen where Did= @Did;

2 C#后台调用

            /// <summary>
        /// @Author:Lucky Hu
        /// @Date:2011-09-10       
        /// @Title:First Test Procedure
        /// 带参数的存储过程
        /// </summary>
        string ConStr = System.Configuration.ConfigurationManager.AppSettings["ConnStr"];
        SqlConnection conn;
        SqlCommand cmd;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                dlbind();
            }
        }
        public void dlbind()
        {
            conn = new SqlConnection(ConStr);
            string cmdText = "SpShowCommen";
            DataSet ds = new DataSet();
            //创建参数列表,并为参数赋值
            SqlParameter[] paras = new SqlParameter[] {
            new SqlParameter("@Did",62)};
            cmd = new SqlCommand(cmdText, conn);
            cmd.Parameters.AddRange(paras);
            cmd.CommandType = CommandType.StoredProcedure;//表明Command对象类型为存储过程
            SqlDataAdapter sdp = new SqlDataAdapter();
            sdp.SelectCommand = cmd;
            sdp.Fill(ds);
            ClassList.DataSource = ds;
            ClassList.DataBind();
        }

效果如下:

 

源码附件:Procedure.rar 

posted @ 2011-09-10 15:16  楠木大叔  阅读(761)  评论(1编辑  收藏  举报