c# - 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。
解决方案
命令参数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
方法里面
推荐阅读
- c# - OpenIdConnectEvents OnAuthorizationCodeReceived 未触发
- javascript - Gatsby 是否提供了一种将 Markdown 渲染的通用 HTML 元素映射到 React 组件的方法?
- c# - 绑定图像未出现在设计时
- javascript - 如何做一个 string.match 条件
- node.js - 温斯顿记录到单独的文件
- ios - 如何在应用中使用 Alamofire 的 NetworkRechabilityManager?
- django - Django, Wagtail admin: handle many to many with `through`
- django - 带有 JWT 的 Django Rest Framework 获取用户信息
- mysql - MySQL - 如何选择具有 1 个条件的所有数据并在必要时以其他条件完成?
- python - s.encode("hex") 和 binascii.hexlify(s) 是否等效?