gpt4 book ai didi

c# - 为什么我们在sql表中插入或更新或删除数据时使用 "@"

转载 作者:行者123 更新时间:2023-11-30 15:34:08 25 4
gpt4 key购买 nike

我只是想知道为什么我们在sql表中插入或更新或删除数据时使用“@”,因为我使用@name如下。

 cmd.Parameters.Add(new SqlParameter("@fname", txtfname.Text));

最佳答案

参见:SqlParameter.ParameterName Property - MSDN

The ParameterName is specified in the form @paramname. You must set ParameterName before executing a SqlCommand that relies on parameters.

@SqlCommand 使用,以便参数的值可以在命令文本中区分

SqlCommand cmd = new SqlCommand("Select * from yourTable where ID = @ID", conn);
^^^^^^^
//This identifies the parameter

如果 @ 没有提供参数名称,则添加它。看下面的源码,(taken from here)

 internal string ParameterNameFixed {
get {
string parameterName = ParameterName;
if ((0 < parameterName.Length) && ('@' != parameterName[0])) {
parameterName = "@" + parameterName;
}
Debug.Assert(parameterName.Length <= TdsEnums.MAX_PARAMETER_NAME_LENGTH, "parameter name too long");
return parameterName;
}
}

编辑:

如果您不对参数使用 @ 符号,请考虑以下情况。

using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
conn.Open();
cmd.CommandText = "SELECT * from yourTable WHERE ID = ID";
cmd.Connection = conn;
cmd.Parameters.AddWithValue("ID", 1);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
}
}

以上将获取所有记录,因为这将转换为 SELECT * from yourTable WHERE 1=1,如果您使用上面的 @ 作为参数 ID,你将只得到针对ID =1

的记录

关于c# - 为什么我们在sql表中插入或更新或删除数据时使用 "@",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16603840/

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