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

前端 未结 2 1526
南旧
南旧 2020-12-12 03:23

I\'m writing a small program in C# that uses SQL to store values into a database at runtime based on input by the user.

The only problem is I can\'t figure out the c

相关标签:
2条回答
  • 2020-12-12 03:48

    Add a parameter to the command before executing it:

    cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
    
    0 讨论(0)
  • 2020-12-12 03:51

    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 );
    
    0 讨论(0)
提交回复
热议问题