use*_*485 1 .net c# sql t-sql 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>
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
存储过程:
CREATE PROCEDURE procedure3
AS
BEGIN
select menuename from menue;
END
GO
Run Code Online (Sandbox Code Playgroud)
你的程序不匹配(procedure3 vs storeprocedure3)
使用此代码
SqlCommand cmd = new SqlCommand("procedure3 ", conn);
Run Code Online (Sandbox Code Playgroud)
并关闭你的连接
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Run Code Online (Sandbox Code Playgroud)
IMO,这是最大和最可能的问题:
catch (Exception sa)
{
Console.WriteLine(sa);
}
Run Code Online (Sandbox Code Playgroud)
我想象它正试图真的很难告诉你什么是错的,但是你沉默了.没有任何理由来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
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,坦率地说,使用像小巧玲珑的工具:
using(SqlConnection conn = Class3.GetConnection())
{
foreach(var obj in conn.Query("whatever",
commandType: CommandType.StoredProcedure))
{
string menuename = obj.menuename;
// do something...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
843 次 |
| 最近记录: |