How to pass variable into SqlCommand statement and insert into database table

£可爱£侵袭症+ 提交于 2019-11-28 14:13:56

Add a parameter to the command before executing it:

cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;

You didn't provide a value for the @ parameter in the SQL statement. The @ symbol indicates a kind of placeholder where you will pass a value through.

Use an SqlParameter object like is seen in this example to pass a value to that placeholder/parameter.

There are many ways to build a parameter object (different overloads). One way, if you follow the same kind of example, is to paste the following code after where your command object is declared:

        // Define a parameter object and its attributes.
        var numParam = new SqlParameter();
        numParam.ParameterName = " @num";
        numParam.SqlDbType = SqlDbType.Int;
        numParam.Value = num; //   <<< THIS IS WHERE YOUR NUMERIC VALUE GOES. 

        // Provide the parameter object to your command to use:
        cmd.Parameters.Add( numParam );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!