Search code examples
c#sqlparameter

SELECT query using SqlParameter isn't working


I'm working on a select query for sql in c#. Trying to use SqlParameter, but when I debug, I throw an exception:

Must declare scalar variable "@p1".

I'm passing values in via textbox to properties in a class Customer. This is what is in my event handler:

var newCustomer = new Customer();
newCustomer.FirstName = textBoxFirstName.Text;
newCustomer.LastName = textBoxLastName.Text;
newCustomer.Address = textBoxAddress.Text;
newCustomer.City = textBoxCity.Text;
newCustomer.State = textBoxState.Text;
newCustomer.Zip = Int32.Parse(textBoxZip.Text);
newCustomer.Phone = Int64.Parse(textBoxPhone1.Text);
newCustomer.Notes = textBoxNotes.Text;

var crochetDataHandler = new CrochetDataHandler();
crochetDataHandler.InsertNewCustomer(newCustomer);

And this is the method I'm calling:

public void InsertNewCustomer(Customer customer)
{
        var insertCustomerString = 
"Insert into Customer1 (FirstName, LastName, Address, City, State, Zip, Phone, Notes) Values (@p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8)";

    SqlCommand newCust = new SqlCommand(insertCustomerString);
    newCust.Parameters.Add(new SqlParameter("@p1", customer.FirstName));
    newCust.Parameters.Add(new SqlParameter("@p2", customer.LastName));
    newCust.Parameters.Add(new SqlParameter("@p3", customer.Address));
    newCust.Parameters.Add(new SqlParameter("@p4", customer.City));
    newCust.Parameters.Add(new SqlParameter("@p5", customer.State));
    newCust.Parameters.Add(new SqlParameter("@p6", customer.Zip));
    newCust.Parameters.Add(new SqlParameter("@p7", customer.Phone));
    newCust.Parameters.Add(new SqlParameter("@p8", customer.Notes));

    newCust.CommandText.ToString();
    InsertRecord(insertCustomerString);

I have seen a few different constructors used for SqlParameter in other questions, but when I try them I get the same exception.


Solution

  • I'm not sure what your InsertRecord method is doing, but you're passing the original string insertCustomerString to it rather than your SqlCommand object. The string knows nothing about what you've done with the parameters, so if InsertRecord is expecting the string to know the parameters' values it'll be disappointed.