C#程序不执行存储过程

C# program does not execute Stored Procedure

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

在 SQL-服务器中使用我的 SP 作为

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

工作得很好。但是从 c# 执行它不会在 table

中创建一个条目
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);
    }
}

我已经尝试捕获一个错误,但是 none。我最后得到的只是

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.

您没有执行命令: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executenonquery?view=netframework-4.8

尝试

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");
        // Execute and get rows affected count. 
       var rowsAffected = cmd.ExecuteNonQuery();
        cn.Close();
    }
    catch (SqlException sqlEx)
    {
        Console.WriteLine(sqlEx.Message);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}