C# 如何在sql查询命令中使用方法输入中存在的参数?
这是我的代码:C# 如何在sql查询命令中使用方法输入中存在的参数?,c#,sql,sql-server,ado.net,C#,Sql,Sql Server,Ado.net,这是我的代码: public void addUser(int id,string username,string password,int accountcredit) { SqlConnection sq1 = new SqlConnection("Data Source=xxx;Initial Catalog=xxxxx;User ID=xx;Password=xxxxxxx"); SqlCommand command = new Sql
public void addUser(int id,string username,string password,int
accountcredit)
{
SqlConnection sq1 = new SqlConnection("Data Source=xxx;Initial Catalog=xxxxx;User ID=xx;Password=xxxxxxx");
SqlCommand command = new SqlCommand("", sq1);
command.CommandText = "insert into userData values(@id,@username,@password,@accountcredit) ";
command.Parameters.AddWithValue("@id", id);
command.Parameters.AddWithValue("@username", username);
command.Parameters.AddWithValue("@password", password);
command.Parameters.AddWithValue("@accountcredit", accountcredit);
SqlDataAdapter da1 = new SqlDataAdapter(command.CommandText,sq1);
}
方法“addUser()”应该获取id、用户名、密码和帐户信用作为参数,并将它们添加到一个用于保存用户记录的表中。我曾尝试使用上面的代码来实现这一点,但我注意到我不能在SQL查询中简单地使用addUser()参数方法。我的问题是如何在SQL查询中使用该方法的参数。真正地
我真的很感谢你们的帮助。要整合一些评论,您需要替换多余的行
SqlDataAdapter da1=新的SqlDataAdapter(command.CommandText,sq1);
与
command.ExecuteOnQuery();
这将执行您针对数据库构造的查询。
我注意到我不能简单地在SQL查询中使用addUser()参数方法
这是什么意思?您不是从SqlCommand调用ExecuteOnQuery方法。当然,您的表中没有添加任何内容。正如Steve所说,这里不需要SqlDataAdapter,您只是忘记了执行查询。这与参数无关。这里还有另一个可能的问题。您没有列出将接收参数值的字段。通过这种方式,您应该确保您已经为该表中的每个字段插入了一个值,并且没有一个字段的IDENTITY属性设置为ON(ID?),请不要。AddWithValue
请参见和和和另一个:这是另一个