2

我有这样的代码:

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();“说

“没有为一个或多个必需参数提供值。”

有人可以帮我吗?

4

2 回答 2

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);
于 2013-02-11T14:45:15.677 回答
1

Talking about on your error message;

"No value given for one or more required parameters."

This message will appears probably one of your parameters is null or zero-length string. Or the reason can be misspelling of your parameters.

Check your query in your database first and look which column gives you an error.

And please, never add your parameters in your sql command. That may cause SQL Injection attack. Always use parameterized query on your queries.

Check out SqlParameterCollection.AddWithValue() method from MSDN.

于 2013-02-11T14:41:55.727 回答