gpt4 book ai didi

c# - SqlCommand 如何处理整数类型的参数?

转载 作者:太空宇宙 更新时间:2023-11-03 19:11:13 26 4
gpt4 key购买 nike

如果我有这个变量:

int value = 4;

将作为一些 sql 参数传递:

SqlCommand sqlcmd = new SqlCommand();
sqlcmd.Parameters.Add(new SqlParameter("@value", value));

会自动转成字符串处理吗?或者它可能会引起一些麻烦吗? IE。当我这样做时:

sqlcmd.ExecuteNonQuery();

最佳答案

始终提供正确的类型,尤其是 int 是危险的。

来自 MSDN :

Use caution when you use this overload of the SqlParameter constructor to specify integer parameter values. Because this overload takes a value of type Object, you must convert the integral value to an Object type when the value is zero, as the following C# example demonstrates:

Parameter = new SqlParameter("@pname", (object)0);

If you do not perform this conversion, the compiler assumes that you are trying to call the SqlParameter (string, SqlDbType) constructor overload.

所以如果你想使用字符串参数,把它转换成正确的类型:

sqlcmd.Parameters.Add(new SqlParameter("@value", value.ToString()));

sqlcmd.Parameters.AddWithValue("@value", value.ToString());

或(带有类型)

var p = new SqlParameter("@value", typeof(string));
p.Value = value.ToString()
sqlcmd.Parameters.Add(p);

关于c# - SqlCommand 如何处理整数类型的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20475761/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com