Parameterize SQL query

前端 未结 5 652
Happy的楠姐
Happy的楠姐 2020-12-04 02:35

Many posts about Parameters in SQL with C# but I am still missing something. I am not getting an error message but no data is inserted. What is missing? I have text boxes na

5条回答
  •  时光取名叫无心
    2020-12-04 02:57

    This will be much shorter:

    using (SqlConnection connection = new SqlConnection(connectionString))
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "INSERT INTO Contacts ([First], [Last], [Address], [City], [State], [ZIP]) VALUES (@first, @last, @address, @city, @state, @zip)";
    
        command.Parameters.AddWithValue("@first", first);
        // or
        // command.Parameters.Add("@first", SqlDbType.Type).Value = first;
        // ...
    
        connection.Open();
        command.ExecuteNonQuery();
    }
    

    But first of all here's what you missed:

    comm.Parameters.Add(firstparam);
    // instead of
    // comm.Parameters.Add("@first", SqlDbType.Text);
    

    and

    command.ExecuteNonQuery();
    

提交回复
热议问题