2

I use SqlDataAdapter and SqlCommandBuilder to perform DML transactions on rows in a SQL Server database.

I am able to add and delete multiple rows in database but update.

This is the code:

SqlDataAdapter da = new SqlDataAdapter(@"select top 1 * from " + tableName, 
ConnectionString);
SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.Update(dt);

I'm trying to use AcceptChanges, so far it doesn't work.

4
  • Are you coming across any error while trying to update? Commented Jun 11, 2015 at 2:51
  • no,i don't get any error Commented Jun 11, 2015 at 2:56
  • Why not use SqlCommand, add sql compatible parameters and then do an executeNonQuery? Commented Jun 11, 2015 at 3:40
  • @meomeo include the cmdBuilder.GetUpdateCommand(); before your da.Update(dt); line and check if your database gets updated. Commented Jun 11, 2015 at 4:07

2 Answers 2

0

This is how I usually do within C#. If you want to give this a try.

//you may put this as a direct string or in a static class when layering
//you can pass table as hard-coded value or as a parameter
String SqlQuery = "UPDATE " +
            " [tableName] " +
            " SET [Column1ToBeUpdated]=@Column1Value," +
            " [Column2ToBeUpdated]=@Column2Value" +
            " WHERE ([ColumnxWithCondition] = @Condition)";

//add OR, AND operators as per your needs
//choose the correct SqlDbType for your column data types

public bool UpdateMyTable(String SqlQuery, Someclass obj)
 {
        SqlCommand sCommand = new SqlCommand(this.SqlQuery, (new SqlConnection(ConnectionString)));

        sCommand.Parameters.Add("@Column1Value", SqlDbType.VarChar).Value = obj.col1Value;
        sCommand.Parameters.Add("@Column2Value", SqlDbType.VarChar).Value = obj.col2Value;
        sCommand.Parameters.Add("@Condition", SqlDbType.VarChar).Value = obj.condition;

        sCommand.Connection.Open();
        var rowsAffected = sCommand.ExecuteNonQuery();
        sCommand.Connection.Close();
        return rowsAffected > 0;
 }

 //if you want to see the number, you may return rowsAffected
Sign up to request clarification or add additional context in comments.

1 Comment

I just noticed that @TimSchmelter has a great answer here with SqlDataAdapter for batch updates. You can try that out.
0

i have found reason, a column is set DateTime type. So, this Column isn't saving to the database.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.