C#中的存储过程

时间:2012-06-26 11:46:45

标签: c# .net sql tsql stored-procedures

我想在c#中使用存储过程。我在sql server中创建存储过程,然后在程序中调用它。但是当我使用断点功能时,我发现当断点跳过循环时,数据不会从数据库中检索出来。

.aspx代码:

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="store" />
<asp:Label ID="Label9" runat="server" Text="Label"></asp:Label>

c#c​​ode:

public void store(object sender, EventArgs ser)
{
    try
    {
        // c reate and open a connection object
        SqlConnection conn = Class3.GetConnection();

        // 1. create a command object identifying the stored procedure
        SqlCommand cmd = new SqlCommand("storeprocedure3", conn);

        // 2. set the command object so it knows to execute a stored procedure
        cmd.CommandType = CommandType.StoredProcedure;

        // 3. add parameter to command, which will be execute the command
        SqlDataReader rdr = cmd.ExecuteReader();

        // iterate through results, printing each to console
        while (rdr.Read())
        {
            Label9.Text = rdr["menuename"].ToString();
        }
    }
    catch (Exception sa)
    {
        Console.WriteLine(sa);
    }
}

存储过程:

CREATE PROCEDURE procedure3     
AS
BEGIN
    select menuename from menue;

END
GO

3 个答案:

答案 0 :(得分:5)

您的计划不匹配( procedure3 vs storeprocedure3

使用此代码

 SqlCommand cmd = new SqlCommand("procedure3 ", conn);

并关闭您的连接

 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

答案 1 :(得分:5)

IMO,这是最大和最可能的问题:

catch (Exception sa)
{
    Console.WriteLine(sa);
}

想象它正在尝试真的很难告诉你什么是错的,但是你让它沉默了。对try / catch这个没有任何理由;如果这不起作用,某些东西是非常错误的 - 让它出错。阅读例外细节。

如果我挑剔(坦白说,我是) - 你需要更多using这里,即

using(SqlConnection conn = Class3.GetConnection())
using(SqlCommand cmd = new SqlCommand("whatever", conn))
{
    cmd.CommandType = CommandType.StoredProcedure;
    using(SqlDataReader rdr = cmd.ExecuteReader())
    {
        while (rdr.Read())
        {
           // do something
        }
    }
}

或者,坦率地说,使用像dapper这样的工具:

using(SqlConnection conn = Class3.GetConnection())
{
    foreach(var obj in conn.Query("whatever",
          commandType: CommandType.StoredProcedure))
    {
        string menuename = obj.menuename;
        // do something...
    }
}

答案 2 :(得分:2)

EXEC procedure会产生任何结果吗?

同样在您的代码中,您已将存储过程引用为storeprocedure3,而实际上过程名称似乎为procedure3

将行更改为:

SqlCommand cmd = new SqlCommand("procedure3", conn);