我有这样的代码:
public int updateFriend(long id, string Firstname, string Lastname, string Nickname, DateTime Birthdate, int Age, string Gender)
{
OleDbConnection con = new OleDbConnection(conString());
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
OleDbCommand cmd = new OleDbCommand(query, con);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
return (rowsAffected);
}
现在问题是,当我点击更新按钮时,它调用方法updateFriend
,然后行"int rowsAffected = cmd.ExecuteNonQuery();
上出现错误“说
“没有给出一个或多个必需参数的值。”
有人可以帮我吗?
答案 0 :(得分:2)
string query = "UPDATE FriendList SET Firstname ='" + Firstname + "', Lastname ='" + Lastname + "',Nickname ='" + Nickname + "',Birthday ='" + Birthdate + "',Age ='" + Age + "', Gender ='" + Gender + "' WHERE ID = " + id;
您将所有参数作为字符串传递,其中一些参数是int,一个是DateTime
。建议您使用Parameters.AddWithValue()
string query = "UPDATE FriendList SET Firstname = @Firstname, Lastname = @Lastname , Nickname = @Nickname, Birthday = @Birthdate, Age = @Age, Gender = @Gender WHERE ID = @id";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("@Firstname", FirstName);
//add rest parameters the same way as above
cmd.Parameters.AddWithValue("@id", id);
答案 1 :(得分:1)
谈论错误消息;
“没有给出一个或多个必需参数的值。”
此消息可能会显示您的一个参数是null
或零长度字符串。或者原因可能是拼写错误的参数。
首先检查数据库中的查询,然后查看哪个列给出错误。
并且,从不在sql命令中添加您的参数。这可能会导致SQL Injection攻击。始终在查询中使用parameterized query
。
从 MSDN 中查看SqlParameterCollection.AddWithValue()
方法。