存储过程使用示例

本文关键字:存储过程 | 更新日期: 2023-09-27 18:26:04

如何在连接字符串中使用存储过程而不是查询。你能建议我编码吗???

存储过程使用示例

开始

string spName = "stored_proc_name";
string idParameterValue = "someId";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
    using (SqlCommand command = new SqlCommand(spName, connection))
    {
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@Id", idParameterValue));
        connection.Open();
        IDbDataAdapter da = new SqlDataAdapter();
        da.SelectCommand = command;
        // (*) Put here a code block of the actual SP execution logic
        // There are different ways of SP execution and it depends on
        // return result set type, see below
    }
}

(*)选择适当的方法:

  1. 将输出结果集保存在数据集中

    // Store output result set in the DataSet
    DataSet ds = ExecuteQuery(da);
    
  2. OR读取单个整数作为存储过程返回值(不是OUT param!)

    IDataReader reader = command.ExecuteReader();
    if (reader != null && reader.Read())
    {
        retValue = (reader.GetInt32(returnParamName));
    }
    
  3. 如果存储过程没有返回任何

    bool successfull = cmd.ExecuteNonQuery() == 1;
    

辅助方法

private static DataSet ExecuteQuery(IDataAdapter da)
{
    DataSet ds = new DataSet("rawData");
    da.Fill(ds);
    ds.Tables[0].TableName = "row";
    foreach (DataColumn c in ds.Tables[0].Columns)
    {
        c.ColumnMapping = MappingType.Attribute;
    }
    return ds;
}
public static class DataReaderExtensions
{  
    public static Int32 GetInt32(this IDataReader rdr, string fieldName)
    {
        int ordinal = rdr.GetOrdinal(fieldName);
        return !rdr.IsDBNull(ordinal) ? rdr.GetInt32(ordinal) : Int32.MinValue;
    }
}

有用的链接:

  • CommandType枚举

您需要定义sql命令-在本例中是对存储过程的调用-然后连接到数据库,发送查询并接收结果。

之后别忘了关闭连接!

csharp站上有一个很好的教程。

我无法在这里描述整个过程,如果你有更详细的问题,请回来问一下——这就是Stackoverflow的用途:)