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

I have the following code in my ASP.NET project and I still cannot understand why my SQL Server table stores the parameter name instead of values. Any help would 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();
+3
source share
1 answer

Remove the quotation marks and use the AddWithValuemethod as follows:

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 using quotation marks, @Firstnameand are @Lastnametreated as actual values ​​instead of parameters. You do not need to use the method AddWithValue, but it is shorter and easier to use. You do not need to create SqlParameterfor each parameter and set each property each time.

+12
source

All Articles