C# - Update SQL Table

21,286

Solution 1

As Michał Turczyn wrote in his answer, you have some problems with your code.
I agree with everything he wrote, but I thought you might benefit from seeing how your code should look like - so here you go:

var connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
var sql = "UPDATE Employees SET LastName = @LastName, FirstName = @FirstName, Title = @Title ... ";// repeat for all variables
try
{
    using(var connection = new SqlConnection(connetionString))
    {
        using(var command = new SqlCommand(sql, connection))
        {
            command.Parameters.Add("@LastName", SqlDbType.NVarChar).Value = Lnamestring;
            command.Parameters.Add("@FirstName", SqlDbType.NVarChar).Value = Fnamestring;
            command.Parameters.Add("@Title", SqlDbType.NVarChar).Value = Titelstring;
            // repeat for all variables....
            connection.Open();
            command.ExecuteNonQuery();
        }       
    }
}
catch (Exception e)
{
    MessageBox.Show($"Failed to update. Error message: {e.Message}");
}

Solution 2

Few issues with your code:

1) Use using, when working with IDisposable objects, in your case connection and command.

2) As suggested in comments, use SqlCommandParameters instead of concatenating strings for security reasons (google "preventing from SQL injections")

3) You don't execute your query! How you want it to make an impact if you don't do it? There's, for example, method like ExecuteNonQuery in SqlCommand class.

Share:
21,286
MansNotHot
Author by

MansNotHot

I said Mans not Hot!

Updated on August 05, 2022

Comments

  • MansNotHot
    MansNotHot almost 2 years

    I want to update my sql table. I was searching here and found solutions on how to go onto that problem. But sadly it just wont update the database. I have no clue what the problem is. I checked to sql command a couple of times for writing mistakes but couldnt find any or fixed them but still sadly nothing. I suppose it's something within the try block but cant find it out.

    This is my code:

    string connetionString = null;
    SqlConnection connection;
    SqlCommand command;
    string sql = null;
    SqlDataReader dataReader;
    connetionString = "Data Source=xxx\\xxx;Initial Catalog=xxx;User ID=xxx;Password=xxx";
    sql = "UPDATE Employees SET LastName = '" + Lnamestring + "', FirstName = '" + Fnamestring + "', Title = '" + Titelstring + "', TitleOfCourtesy = '" + ToCstring + "', BirthDate = '" + Birthdatestring + "', HireDate = '" + Hiredatestring + "', Address = '" + Adressstring + "', City = '" + Citystring + "', Region = '" + Regionstring + "', PostalCode = '" + Postalstring + "', Country = '" + Countrystring + "', HomePhone = '" + Phonestring + "', Extension = '" + Extensionsstring + "', Notes = '" + Notesstring + "', ReportsTo = '" + ReportTostring + "' WHERE EmployeeID = '" + IDstring + "'; ";
    connection = new SqlConnection(connetionString);
    try
    {
        connection.Open();
        command = new SqlCommand(sql, connection);
        SqlDataAdapter sqlDataAdap = new SqlDataAdapter(command);
    
        command.Dispose();
        connection.Close();
        MessageBox.Show("workd ! ");
    
    }
    catch (Exception ex)
    {
        MessageBox.Show("Can not open connection ! ");
    }
    

    I hope someone can help me find my mistake.

    EDIT: when i try it out it seems to work as the windows pops up with "workd" but the database is unchanged.

    • IronAces
      IronAces over 6 years
      What exactly is happening? Is an error occurring? P.S Make use of Using Statement P.P.S Make use of parameterisation
    • MansNotHot
      MansNotHot over 6 years
      just edited it at the bottom
    • rene
      rene over 6 years
      please use SqlCommandParameters instead of string concat
    • rene
      rene over 6 years
      you don't execute the command, at all.
    • Nino
      Nino over 6 years
      try with command.ExecuteNonQuery(); before command.Dispose();
    • JB's
      JB's over 6 years
      Try using Integrated Security = false when providing login credentials for connection string link and add providerName="System.Data.SqlClient" to connection string too.
    • Zohar Peled
      Zohar Peled over 6 years
      Changed the wrong MySql tag to the correct SQL Server tag.
  • RealCheeseLord
    RealCheeseLord over 6 years
    add a few words of explaination, as to why this is a solution to the question
  • MansNotHot
    MansNotHot over 6 years
    Thanks worked like a charm and yes it was very helpful seeing how it was meant. Because im coding in C# for two days now :)
  • KiynL
    KiynL about 2 years
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.