Вопрос

I'm using a data reader, connection and SqlCommand as static variables... in my first sub procedure, I have a select statement with a LIKE clause that searches based on user input for matching records... the 2nd sub procedure cycles through the records, by calling the datareader again.

This code is for the third sub procedure which is supposed to update 2 tables based on if the user changes any of the text fields which currently hold the previously loaded recorded.

If I change the first table (first middle or last name) and hit the Save button, then it works, but I'm having issues getting any of the address fields to load.

How can I have multiple data readers / Update statements in one sub procedure? Logically the code makes sense to me but maybe I'm not looking at right.

protected void btnSave_Click(object sender, EventArgs e)
{
    var conn = new System.Data.SqlClient.SqlConnection(@"Server=LOCALHOST;Database=AdventureWorks2012;Trusted_Connection=True;");

    try
    {
        conn.Open();
    }
    catch (Exception ex)
    {
        lblSearch.Text = "Connection Error! " + ex;
    }

    var cmd1 = new System.Data.SqlClient.SqlCommand("UPDATE Person.Person SET FirstName=@First, MiddleName=@Middle, LastName=@Last WHERE FirstName=@First", conn);
    var cmd2 = new System.Data.SqlClient.SqlCommand("UPDATE Person.Address SET AddressLine1=@Add1, AddressLine2=@Add2, City=@City, PostalCode=@Zip WHERE AddressLine1=@Add1", conn);
    cmd1.Parameters.AddWithValue("@First", txtFirst.Text);
    cmd1.Parameters.AddWithValue("@Middle", txtMiddle.Text);
    cmd1.Parameters.AddWithValue("@Last", txtLast.Text);
    cmd2.Parameters.AddWithValue("@Add1", txtAddress1.Text);
    cmd2.Parameters.AddWithValue("@Add2", txtAddress2.Text);
    cmd2.Parameters.AddWithValue("@City", txtCity.Text);
    cmd2.Parameters.AddWithValue("@Zip", txtZip.Text);

    try
    {
        dReader1 = cmd1.ExecuteReader();
    }
    catch(Exception ex)
    {
        lblSearch.Text = "Error: " + ex;
    }

    try 
    {
        dReader2 = cmd2.ExecuteReader();
    }
    catch (Exception ex)
    {
        lblSearch.Text = "Error: " + ex;
    }

    try
    {
        dReader1.Read();
    }
    catch (Exception ex)
    {
        lblSearch.Text = "Error: " + ex;
    }

    try
    {
        dReader2.Read();
    }
    catch (Exception ex)
    {
          lblSearch.Text = "Error: " + ex;
    }
}
Это было полезно?

Решение

2 things:

  1. Dont use a datareader for updating data. Use an ExecuteNonQuery.
  2. With Try..Catch blocks, code always returns after the block so if there was an error in say your connection, it will set the label but then continue with the code below it, attempting to run your commands.

Otherwise, your code should work, for what is shown here. Just dont use the datareaders.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top