SqlCommand参数添加与AddWithValue [重复]

问题描述 投票:24回答:1

这个问题在这里已有答案:

我什么时候应该使用Parameters. Add/AddWithValue?在下面的MSDN示例中,他们将Parameters.Add用于int,使用Parameters.AddWithValue用于string

command.Parameters.Add("@ID", SqlDbType.Int);
command.Parameters["@ID"].Value = customerID;

command.Parameters.AddWithValue("@demographics", demoXml);

什么是最好用于datetime

c# parameters sqlcommand
1个回答
36
投票

使用Add如果你想通过更多的工作使所有显而易见。如果你很懒,请使用AddWithValueAddWithValue将导出其值的参数类型,因此请确保它是正确的类型。例如,如果这是正确的类型,您应该将string解析为int

有一个原因可以避免Add,如果你的参数类型是int,你必须小心overload that takes the parameter-name and an object,然后another overload is chosen with the SqlDbType-enum

来自remarks(方法超载现在甚至是obsolete):

使用SqlParameterCollection.Add方法的此重载指定整数参数值时请小心。因为此重载采用Object类型的值,所以当值为零时,必须将整数值转换为Object类型...如果不执行此转换,编译器会假定您尝试调用SqlParameterCollection.Add(string, SqlDbType)重载。

© www.soinside.com 2019 - 2024. All rights reserved.