我想在 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#代码:
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
最佳答案
IMO,这是最大也是最有可能出现的问题:
catch (Exception sa)
{
Console.WriteLine(sa);
}
我想象它真的很努力地想告诉你哪里出了问题,但你却让它沉默了。 没有任何理由try
/catch
;如果这不起作用,有什么地方很不对 - 让它出错。阅读异常详细信息。
如果我很挑剔(坦率地说,我确实很挑剔)- 您需要更多在这里使用
,即
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...
}
}
关于c# - C# 中的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11206641/