2

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.

7
  • What exactly is happening? Is an error occurring? P.S Make use of Using Statement P.P.S Make use of parameterisation Commented Sep 6, 2017 at 7:02
  • just edited it at the bottom Commented Sep 6, 2017 at 7:03
  • please use SqlCommandParameters instead of string concat Commented Sep 6, 2017 at 7:03
  • 6
    you don't execute the command, at all. Commented Sep 6, 2017 at 7:04
  • 1
    try with command.ExecuteNonQuery(); before command.Dispose(); Commented Sep 6, 2017 at 7:05

5 Answers 5

10

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}");
}
Sign up to request clarification or add additional context in comments.

1 Comment

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 :)
3

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.

Comments

0
string connetionString = null;
SqlConnection connection;
SqlCommand command;
string sql = null;
SqlDataReader dataReader;
connetionString = "Data Source=EVOPC18\\PMSMART;Initial Catalog=NORTHWND;User ID=test;Password=test";
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.ExecuteNonQuery();

    command.Dispose();
    connection.Close();
    MessageBox.Show("workd ! ");

}
catch (Exception ex)
{
    MessageBox.Show("Can not open connection ! ");
}
  1. Don't forget to execute the command
  2. Try to get the stacktrace or error message from Exception as much as possible. For example: MessageBox.Show($"Can not open connection ! {e.GetBaseException().Message}, {e.StackTrace}");

Comments

0
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;

cmd.CommandText = "update CarTb1 set ( @RegNo , @MOdel , @Price , @Available  where @Brand);";
cmd.CommandType = System.Data.CommandType.Text;
Da = new SqlDataAdapter("Select * From CarTb1", con);
Da.Fill(Dt);
cmd.Parameters.AddWithValue("@RegNo", txtRegnumber.Text);
cmd.Parameters.AddWithValue("@Brand", combBrand.Text);
cmd.Parameters.AddWithValue("@Model", txtModel.Text);
cmd.Parameters.AddWithValue("@Price", txtPrice.Text);
cmd.Parameters.AddWithValue("@Color", txtColor.Text);
cmd.Parameters.AddWithValue("@Available", combAvailable.Text);
        con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Record Edited Successfally");
con.Close();
ClearData();

1 Comment

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.
-1

Please use the ExecuteNonQuery() instead of SqlDataAdapter:

connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show("workd ! ");

1 Comment

add a few words of explaination, as to why this is a solution to the question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.