MansNotHot
MansNotHot

Reputation: 293

C# - Update SQL Table

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.

Upvotes: 2

Views: 29057

Answers (5)

hady khater
hady khater

Reputation: 1

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();

Upvotes: 0

saravanan
saravanan

Reputation: 1

Please use the ExecuteNonQuery() instead of SqlDataAdapter:

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

Upvotes: -1

Zohar Peled
Zohar Peled

Reputation: 82474

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}");
}

Upvotes: 10

Ray Krungkaew
Ray Krungkaew

Reputation: 6965

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}");

Upvotes: 0

Michał Turczyn
Michał Turczyn

Reputation: 37337

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.

Upvotes: 3

Related Questions