C#程序不执行存储过程

标签 c# sql-server stored-procedures ado.net

我想通过 C# 在 Azure SQL-Server 上运行我的存储过程,但它不起作用,我不知道如何找出原因。该存储过程有两个输入参数并根据这些将信息插入到表中。这样我就可以在表中看到是否有新条目(SP 是否有效)。

在 SQL-Server 中使用我的 SP

exec Commentary.Add_Information @ID = 34926, @year = '2020'  

工作得很好。但从 c# 执行它不会在表中创建条目

public void CreateBasicInformation()
{
    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
    builder.DataSource = "myServer.database.windows.net";
    builder.UserID = "admin";
    builder.Password = "myPass";
    builder.InitialCatalog = "myDB";

    try
    {
        SqlConnection cn = new SqlConnection(builder.ConnectionString);
        cn.Open();
        SqlCommand cmd = new SqlCommand("Add_Information", cn);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@ID", "34926");
        cmd.Parameters.AddWithValue("@year", "2020");
        cn.Close();
    }
    catch (SqlException sqlEx)
    {
        Console.WriteLine(sqlEx.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

我已经 try catch 错误,但没有发现错误。我最后得到的只是

The program '[9480] test_SP.exe' has exited with code 0 (0x0).

代码中是否有错误,或者有什么方法可以找出为什么 C# 和 SP 不能一起工作?

最佳答案

您实际上并没有执行命令,您需要将以下行添加到 execute它:

cmd.ExecuteNonQuery();
cn.Close();

还强烈建议使用 Using statement现在:

The purpose of the using statement is to provide a simpler way to specify when the unmanaged resource is needed by your program, and when it is no longer needed.

关于C#程序不执行存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59284009/

相关文章:

Delphi Postgres 存储过程

php - 从多个插入查询中恢复生成的 ID

c# - 搜索大量大文本列表的最快方法

c# - .NET Framework 4.0 是否支持 Websocket 通信的数据帧?

sql-server - 带 CASE 的 GROUP BY - sql

sql-server - SQL Server CASE 子句中的比较

c# - 我可以使用不同的 DataTrigger 绑定(bind)重用样式吗?

c# - XAML/C# API 中是否包含 Javascript API 中的所有功能?

sql查询-用同一个表中的记录值更新现有字段

SQL Proc 在更新/更快的机器上变慢?