SqlCommand Parameters Add vs. AddWithValue [duplicate]

元气小坏坏 提交于 2019-11-26 04:50:09

问题


When should I use Parameters. Add/AddWithValue? In the following MSDN example they use Parameters.Add for int and Parameters.AddWithValue for string

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

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

What is the best to use for datetime


回答1:


Use Add if you want to make all explicit with a little bit more work. Use AddWithValue if you are lazy. AddWithValue will derive the type of the parameter of it's value, so ensure that it's the correct type. You should for example parse a string to int if that is the correct type.

There is one reason to avoid Add, if your parameter type is int you must be careful with the overload that takes the parameter-name and an object since then another overload is chosen with the SqlDbType-enum.

From remarks (method overload is even obsolete now):

Use caution when you are using this overload of the SqlParameterCollection.Add method to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero ... If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameterCollection.Add(string, SqlDbType) overload.



来源:https://stackoverflow.com/questions/21110001/sqlcommand-parameters-add-vs-addwithvalue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!