How To Pass Variable Into Sqlcommand Statement And Insert Into Database Table
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 correct Sql syntax
Solution 1:
Add a parameter to the command before executing it:
cmd.Parameters.Add("@num", SqlDbType.Int).Value = num;
Solution 2:
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 );
Post a Comment for "How To Pass Variable Into Sqlcommand Statement And Insert Into Database Table"