首页 > 解决方案 > C# - 如何将带有@Parameters 的插入发送到数据库连接类

问题描述

让我的插入正常工作有点问题。当我在同一个方法中运行插入时,它可以完美地工作......但是当我尝试将插入语句发送到我的新 Connection 类(我将处理所有数据库请求)时,我收到以下错误。

注意:我使用的是 C# 和 Microsoft SQL Server。

System.Data.SqlClient.SqlException (0x80131904): Must declare the scalar variable "@CollectionGroupID".

我相信我没有发送参数,但是我不确定执行此操作的最佳方法。

这是我的 AddGame 方法:

public static void AddGame(int gameId)
    {

        string statement = "INSERT INTO Collection (CollectionGroupID, SharedID, UserID, GameID, Owned, Favorited, WishList, DeletedIndicator, AddUser, AddDate, ModUser, ModDate) VALUES (@CollectionGroupID, @SharedID, @UserID, @GameID, @Owned, @Favorited, @WishList, @DeletedIndicator, @AddUser, @AddDate, @ModUser, @ModDate)";

        using (SqlCommand cmd = new SqlCommand())
        {

            cmd.Parameters.AddWithValue("@CollectionGroupID", "0");
            cmd.Parameters.AddWithValue("@SharedID", "0");
            cmd.Parameters.AddWithValue("@UserID", "0"); 
            cmd.Parameters.AddWithValue("@GameID", gameId);
            cmd.Parameters.AddWithValue("@Owned", "Y");
            cmd.Parameters.AddWithValue("@Favorited", "N");
            cmd.Parameters.AddWithValue("@WishList", "N");
            cmd.Parameters.AddWithValue("@DeletedIndicator", "N");
            cmd.Parameters.AddWithValue("@AddUser", "test/admin");
            cmd.Parameters.AddWithValue("@AddDate", DateTime.Now);
            cmd.Parameters.AddWithValue("@ModUser", "test/admin");
            cmd.Parameters.AddWithValue("@ModDate", DateTime.Now);


            Connection.Open();
            Connection.Statement(statement);
            Connection.Close();


        }
    }

这是我的 Connection 类中的 Statement 方法

public static void Statement(string sql)
    {
        Console.WriteLine("Attempting to submit data to the database...");

        try
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
        }
        catch (SqlException e)
        {
            Console.WriteLine(e);
        }

    }

我觉得也许我忽略了一个简单的解决方案。任何帮助表示赞赏!

——特拉维斯·W。

标签: c#sqlsql-serverasp.net-core.net-core

解决方案


命令参数SqlCommand在您的AddGame方法中定义

您将原始 Sql 传递给该Statement方法,并且在该方法内部创建另一个SqlCommand未定义参数的方法。这就是为什么没有传入参数的原因。

你应该这样做

using (SqlConnection connection = new SqlConnection(connectionString))
{
//OR using (SqlConnection connection = Connection.Open())
//If you want to keep your Connection class to avoid having to pass in connection string.  
    using (SqlCommand cmd = new SqlCommand(statement, connection))
    {
        ...
        cmd.ExecuteNonQuery ()
    }
}

在你的AddGame方法里面


推荐阅读