使用DbConnection执行存储过程

时间:2010-12-30 09:08:38

标签: .net stored-procedures dbconnection

我需要在数据库上执行存储过程。到目前为止,这是我的工作:

protected DbProviderFactory dbProviderFactory;
this.dbProviderFactory = DalFactory.GetFactory(this.adapterConfiguration);

DbConnection dbConnection = dbProviderFactory.CreateConnection();

dbConnection.ConnectionString = this.adapterConfiguration.DatabaseInformation.ExternalDatabaseInformation.connectionString;
            try
            {
                dbConnection.Open();
            }
            catch (Exception e)
            {

                throw;
            }

我怀疑DbCommand会这样做,但没有找到任何工作。假设必须执行名为“initialize”的存储过程。我该怎么做?

3 个答案:

答案 0 :(得分:10)

对于SqlServer,这可能是这样的:

DbCommand command = new SqlCommand();
command.CommandType = System.Data.CommandType.StoredProcedure;
command.CommandText = "<your stored proc>";
command.Connection = dbConnection;

SqlParameter param1 = new SqlParameter("<your parameter>", MyVar);
command.Parameters.Add(param1);
//[...]

SqlParameter returnValue = new SqlParameter("ReturnValue", User);
returnValue.Direction = System.Data.ParameterDirection.ReturnValue;
command.Parameters.Add(returnValue);

command.Connection.Open();
command.ExecuteNonQuery();
int result = (int)command.Parameters["ReturnValue"].Value;
command.Connection.Close();

答案 1 :(得分:2)

创建命令,命令文本应该是SP的名称,命令类型应该是StoredProcedure。

答案 2 :(得分:0)

我在我的大部分应用中都在进行动态查询,但也有EF。我传递一个_ctx EF DbContext来运行我的存储过程。我确信在sql中有一种方法可以做到这一点,但我还没想到它。

            using (_ctx)
            {
                if (_ctx.Database.Connection.State != ConnectionState.Open)
                    _ctx.Database.Connection.Open();
                foreach (var name in _tableNames)
                {
                    using (var cmd = _ctx.Database.Connection.CreateCommand())
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.CommandText = @"UpdateRMRowsToUpload";
                        cmd.Parameters.Add(new SqlParameter("@tableName", SqlDbType.VarChar));
                        cmd.Parameters["@tableName"].Direction = Input;
                        cmd.Parameters["@tableName"].Value = name;
                        cmd.ExecuteNonQuery();
                    }
                }
                if (_ctx.Database.Connection.State == ConnectionState.Open)
                    _ctx.Database.Connection.Close();
            }