让我的插入正常工作有点问题。当我在同一个方法中运行 insert all 时,它完美无缺……但是,当我尝试将 Insert 语句发送到我的新 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。
命令参数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
方法里面
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句