为什么我在SQL表中获得@firstname和@lastname?

时间:2014-02-18 00:20:32

标签: c# asp.net sql sql-server

我的ASP.NET项目中有以下代码,我仍然无法弄清楚为什么我的SQL Server表保存参数名称而不是值。任何帮助将不胜感激。

[WebMethod]
public static void InsertMethod(string firstname, string lastname)
{
    SqlConnection con = new SqlConnection(@"Data Source=KIMBERLY\SQLSERVER02;Initial Catalog=Chalegh;User ID=***;Password=***");
    SqlCommand cmd = new SqlCommand("insert into TestTable values('@Firstname','@Lastname')", con);

    SqlParameter paramFirstName = new SqlParameter();
    paramFirstName.ParameterName = "@Firstname";
    paramFirstName.Value = firstname;
    cmd.Parameters.Add(paramFirstName);

    SqlParameter paramLastName = new SqlParameter();
    paramLastName.ParameterName = "@Lastname";
    paramLastName.Value = lastname;
    cmd.Parameters.Add(paramLastName);

    con.Open();
    cmd.ExecuteNonQuery();

1 个答案:

答案 0 :(得分:12)

删除引号并使用AddWithValue方法,如下所示:

SqlCommand cmd = new SqlCommand("insert into TestTable values(@Firstname,@Lastname)", con);
cmd.Parameters.AddWithValue("@Firstname",firstname);
cmd.Parameters.AddWithValue("@Lastname",lastname);

您的实际问题是引号。使用引号时@Firstname@Lastname被视为实际值而不是参数。您不必使用{ {1}}方法但它更短且易于使用。您不需要为每个参数创建AddWithValue并逐个设置每个属性。