Why do we need SqlCeCommand.Parameters.AddWithValue() to Insert a value?

安稳与你 提交于 2019-12-20 05:23:09

问题


I have a C# WPF desktop application which uses SQL Compact 3.5 as its embedded database. In the insertion function it has

using (SqlCeCommand com = new SqlCeCommand(
    "INSERT INTO FooTable VALUES(@num)", con))
{
    com.Parameters.AddWithValue("@num", num);
    com.ExecuteNonQuery();
}

I don't get what the com.Parameters.AddWithValue() is about. I commented out this line of code and the insertion function run exactly the same. I thought ExecuteNonQuery carries out the insertion, so what is this Parameters.AddWithValue thing?


回答1:


@num is a TSQL parameter. Without AddWithValue(@num, num) this is neither defined nor assigned a value. It simply will not work with the parameter omitted, and even if it did: where would it get your chosen value (num) from? The absolute best it could do would be to use null which was not your intent; more typically it would simply fail to execute (are you sure you aren't swallowing an exception somewhere?).

Note that concatenating the value into the string itself is not recommended; it would cause a SQL injection risk, and can reduce performance (plan re-use; not sure this applies to CE though - CE might very well not bother with cached plans).



来源:https://stackoverflow.com/questions/5592609/why-do-we-need-sqlcecommand-parameters-addwithvalue-to-insert-a-value

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