简体   繁体   中英

Why do I get @firstname and @lastname in my SQL table?

I have the following code in my ASP.NET project and I still can't figure out why is my SQL Server table saving the parameters name instead of the values. Any help will be appreciated.

[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();

Remove quotation marks and use AddWithValue method like this:

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

Your actual problem is quotation marks .When you use quotation marks @Firstname and @Lastname are treated as actual values instead of parameters.You don't have to use AddWithValue method but it's shorter and easy to use.You don't need to create SqlParameter for each parameter and set each property one by one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM