• c#,调用存储过程


    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Data.SqlClient;
    using System.Collections;
    using System.Data;

    namespace TestWindow
    {

        public class StoreProcedure
        {
            // 连接字符串。
            private string connectionString;
            // 存储过程名称。
            private string storeProcedureName;

            //// <summary>
            /// 初始化 DataAccessHelper.StoreProceduer 对象。
            /// </summary>
            /// <param name="connectionString">数据库连接字符串。</param>

            public StoreProcedure(string connectionString)
            {
                this.connectionString = connectionString;
            }

            //// <summary>
            /// 初始化 DataAccessHelper.StoreProceduer 对象。
            /// </summary>
            /// <param name="connectionString">数据库连接字符串。</param>
            /// <param name="storeProcedureName">存储过程名称。</param>
            public StoreProcedure(string storeProcedureName, string connectionString)
            {
                this.connectionString = connectionString;
                this.storeProcedureName = storeProcedureName;
            }

            //// <summary>
            /// 获取或设置存储过程名称。
            /// </summary>
            public string StoreProcedureName
            {
                get { return this.storeProcedureName; }
                set { this.storeProcedureName = value; }
            }

            //// <summary>
            /// 执行操作类(Insert/Delete/Update)存储过程。
            /// </summary>
            /// <param name="paraValues">传递给存储过程的参数值列表。</param>
            /// <returns>受影响的行数。</returns>
            public int ExecuteNonQuery(params object[] paraValues)
            {

                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);

                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        connection.Open();
                        int affectedRowsCount = command.ExecuteNonQuery();
                        return affectedRowsCount;
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            //// <summary>
            /// 执行存储过程,返回 System.Data.DataTable。
            /// </summary>
            /// <param name="paraValues">传递给存储过程的参数值列表。</param>
            /// <returns>包含查询结果的 System.Data.DataTable。</returns>
            public DataTable ExecuteDataTable(params object[] paraValues)
            {

                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);

                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        DataTable dataTable = new DataTable();
                        adapter.Fill(dataTable);
                        return dataTable;
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            //// <summary>
            /// 执行存储过程,填充指定的 System.Data.DataTable。
            /// </summary>
            /// <param name="dataTable">用于填充查询结果的 System.Data.DataTable。</param>
            /// <param name="paraValues">传递给存储过程的参数值列表。</param>
            public void ExecuteFillDataTable(DataTable dataTable, params object[] paraValues)
            {

                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);

                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        connection.Open();
                        SqlDataAdapter adapter = new SqlDataAdapter(command);
                        adapter.Fill(dataTable);
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            //// <summary>
            /// 执行存储过程返回 System.Data.SqlClient.SqlDataReader,
            /// 在 System.Data.SqlClient.SqlDataReader 对象关闭时,数据库连接自动关闭。
            /// </summary>
            /// <param name="paraValues">传递给存储过程的参数值列表。</param>
            /// <returns>包含查询结果的 System.Data.SqlClient.SqlDataReader 对象。</returns>
            public SqlDataReader ExecuteDataReader(params object[] paraValues)
            {

                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);

                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        connection.Open();
                        return command.ExecuteReader(CommandBehavior.CloseConnection);
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            //// <summary>
            /// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行。
            /// </summary>
            /// <param name="paraValues">传递给存储过程的参数值列表。</param>
            /// <returns>结果集中第一行的第一列或空引用(如果结果集为空)。</returns>
            public object ExecuteScalar(params object[] paraValues)
            {

                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);

                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        connection.Open();
                        object result = command.ExecuteScalar();
                        //string r = command.Parameters[1].Value.ToString();
                        return result;
                    }
                    catch
                    {
                        throw;
                    }
                }
            }

            //// <summary>
            /// 从在 System.Data.SqlClient.SqlCommand 中指定的存储过程中检索参数信息并填充指定的 
            /// System.Data.SqlClient.SqlCommand 对象的 System.Data.SqlClient.SqlCommand.Parameters 集  合。
            /// </summary>
            /// <param name="sqlCommand">将从其中导出参数信息的存储过程的 System.Data.SqlClient.SqlCommand 对象。</param>
            internal void DeriveParameters(SqlCommand sqlCommand)
            {
                try
                {
                    sqlCommand.Connection.Open();
                    SqlCommandBuilder.DeriveParameters(sqlCommand);
                    sqlCommand.Connection.Close();
                }
                catch
                {
                    if (sqlCommand.Connection != null)
                    {
                        sqlCommand.Connection.Close();
                    }
                    throw;
                }
            }

            // 用指定的参数值列表为存储过程参数赋值。
            private void AssignParameterValues(SqlCommand sqlCommand, params object[] paraValues)
            {
                if (paraValues != null)
                {
                    if ((sqlCommand.Parameters.Count - 1) != paraValues.Length)
                    {
                        throw new ArgumentNullException("The number of parameters does not match number of values for stored procedure.");
                    }
                    for (int i = 0; i < paraValues.Length; i++)
                    {
                        sqlCommand.Parameters[i + 1].Value = (paraValues[i] == null) ? DBNull.Value : paraValues[i];
                    }
                }
            }

            // 创建用于执行存储过程的 SqlCommand。
            private SqlCommand CreateSqlCommand(SqlConnection connection)
            {

                SqlCommand command = new SqlCommand(this.storeProcedureName, connection);
                command.CommandType = CommandType.StoredProcedure;

                return command;
            }

    //-------------------------------------这一部分是我完善的,因为没有执行后返回存储过程中的返回值的函数-----------------------

            /// <summary>
            /// 执行存储过程,返回存储过程定义的返回值,注意存储过程中参数(paraValues)如果为返回值赋为空,其它值位置对应好
            /// </summary>
            /// <param name="output">返回存储过程中定义的返回值数组</param>
            /// <param name="outParaNum">存储过程中返回值的个数</param>
            /// <param name="paraValues">存储过程全部参数值</param>
           
            public void ExecProcOutput(out object[] output, int outParaNum, params object[] paraValues)
            {
                using (SqlConnection connection = new SqlConnection(this.connectionString))
                {

                    SqlCommand command = this.CreateSqlCommand(connection);
                    output = new object[outParaNum];//存储过程中返回值的个数
                    try
                    {
                        this.DeriveParameters(command);
                        this.AssignParameterValues(command, paraValues);
                        connection.Open();
                        command.ExecuteNonQuery();
                        for (int i = 0; i < outParaNum; i++)//将存储过程返回的参数值返回到程序中
                        {
                            output[i] = command.Parameters[1].Value;
                        }                    
                    }
                    catch
                    {
                        throw;
                    }
                }
            }
        }
    }

    调用实例:

    网上也没有个具体的调用实例,我这里加一个大家参考

    存储过程:使用student数据库,数据很简单自己去看就可以了

    创建存储过程:第一个是有返回值的,第二个是普通查询

    if exists(select name from sysobjects where name='checkUserName' and type='p')
     drop proc checkUserName
    go
    create proc checkUserName
     (@checkResult int output,
      @userName varchar(20),
      @userID varchar(20))
    as
     if exists(select * from student_table where sname=@userName and studentID=@userID)
     set @checkResult=1 --通过验证
     else if exists(select * from student_table where sname=@userName)
     set @checkResult=2 --用户密码错误
     else 
     set @checkResult=0 --用户不存在
    return isNull(@checkResult,2)
    go

    --以下是执行第一个存储过程在sql server 2005中
    declare @checkResult int --声明一个返回值的变量
    exec checkUserName @checkResult output,'g','123' --执行
    select case @checkResult --select 

       when 1 then '成功'
       when 0 then '不存在'
       when 2 then '密码不正确'
       end as  '验证结果'

    --第二个存储过程,普通查询

    use student
    if exists(select * from sysobjects where type='p' and name='studentProc')
     drop proc studentProc
    go
    create proc studentProc
     (@studentName varchar(20),
      @studentID varchar(20))
    as
     select * from student_table where sname=@studentName and studentID=@studentID
    --执行存储过程

    go

    exec studentProc 'g','123'

    private void button1_Click(object sender, EventArgs e)
            {
                
                SqlConnection conn = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand();

    //---------注释部分是我普通的执行存储过程的语句,很繁琐吧...
                //cmd.Connection = conn;
                //conn.Open();
                //cmd.CommandText = "checkUserName";
                //cmd.CommandType = CommandType.StoredProcedure;
                //cmd.Parameters.Add("@userName", SqlDbType.VarChar);
                //cmd.Parameters["@userName"].Value = this.textBox1.Text.Trim();
                //cmd.Parameters.Add("@userID", SqlDbType.VarChar);
                //cmd.Parameters["@userID"].Value = this.textBox2.Text.Trim();
                //cmd.Parameters.Add("@checkResult", SqlDbType.Int);
                //cmd.Parameters["@checkResult"].Direction = ParameterDirection.Output;
                //cmd.ExecuteNonQuery();studentProc

    //---------使用执行存储过程帮手的类来完成.........简单啊!
                StoreProcedure sp = new StoreProcedure("checkUserName", connString);//类的对象
                Object[] paraValues = new object[3];//注意,这里是存储过程中全部的参数,一共有三个,还要注意顺序啊,返回值是第一个,那么赋值时第一个参数就为空
                
                paraValues[1] = this.textBox1.Text.Trim();//从第二个参数开始赋值
                paraValues[2] = this.textBox2.Text.Trim();
                object[] output注意,这里是用来保存,存储过程中定义的返回值

                sp.ExecProcOutput(out output,1, paraValues);//调用我们前面定义的方法,这里我就随便写了一个,能完成功能,大家改进
                //object o = sp.ExecuteScalar(paraValues);//这个是查询的那个存储过程调用,很简单,不多说了

    //---------下面就是验证了...看看,这样做是不是很简单的执行了存储过程.....
                switch (Convert.ToInt32(output[0]))
                { 
                    case 0:
                        this.label4.Text = "用户不存在";
                        break;
                    case 1:
                        this.label4.Text = "登录成功";
                        break;
                    case 2:
                        this.label4.Text = "密码不正确";
                        break;
                    default:
                        break;
                }
            }

    好了..就到这里...我这也是看贴子做完写点感受..也增加自己的印象.............积累中..............

    --------------------以下是在C# vs 2005中使用上面我面定义的类来执行存储过程------------

    界面,很简单就是测试

  • 相关阅读:
    FineAdmin.Mvc 使用ok-admin+ASP.NET MVC搭建的通用权限后台管理系统
    ASP.NET MVC Liu_Cabbage 个人博客
    ASP.NET MVC 通用角色权限管理系统
    js/jquery 判断节点是否存在
    jquery myscroll文字上下无缝滚动插件 简单使用
    使用DATEADD() DATEDIFF() 函数获取时间查询条件
    input 设置 display:none后 jquery无法给input赋值
    ASP.NET MVC QQ互联接入
    修改HTTPS加密协议TLS1.0为TLS1.2
    IIS设置网站为HTTPS并且将HTTP重定向到HTTPS
  • 原文地址:https://www.cnblogs.com/mingdep/p/4758143.html
Copyright © 2020-2023  润新知