请注意,它Paramters.Add
具有接受字符串和 DbType 的重载,因此您不必调用 Parameter 构造函数。您可以替换当前使用的行来添加新参数:
command.Parameters.Add(new SqlParameter("@Firstname", SqlDbType.NVarChar)).Value = TextBox1.Text;
使用以下较短(但功能等效)的行:
command.Parameters.Add("@Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
如果要添加更多参数,只需将它们添加到命令的参数属性中,如下所示:
SqlCommand command = new SqlCommand("inserting", con);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@Firstname", SqlDbType.NVarChar).Value = TextBox1.Text;
command.Parameters.Add("@Lastname", SqlDbType.NVarChar).Value = TextBox2.Text;
除此之外,您是否尝试过使用Parameters.AddWithValue?如果列的数据类型映射到 C# 中值的类型,则可以使用它。您可以在此处找到 C# 到 SQL Server 数据类型的映射。
你会像这样使用它:
// Assume your sproc has a parameter named @Age that is a SqlInt32 type
int age = 5;
// Since age is a C# int (Int32), AddWithValue will automatically set
// the DbType of our new paramter to SqlInt32.
command.Parameters.AddWithValue("@Age", 5);
如果你需要指定SqlDbType,AddWithValue返回你刚刚添加的参数,所以就像在最后添加一个额外的语句来设置DbType属性一样简单,虽然此时你最好使用原始的.Add功能和设置值。
command.Parameters.AddWithValue("@Firstname", TextBox1.Text).DbType = SqlDbType.NVarChar;