简体   繁体   中英

C# ADO.NET UPDATE doesn't change database record, but still returns 1 affected row(s)

I'm trying to update values in a table, and as far as I can tell there is nothing wrong with the code. It even returns 1 row(s) affected like wanted, but when I look in the database the record has not changed. I'd appreciate any help you could offer.

public void UpdateContactInDB(int IDtoUpdate, string editedColumn, string value)
    {
        using (connection)
        {
            SqlCommand command = new SqlCommand("UPDATE ContactSet SET @column = @value WHERE Id = @ID", connection);
            command.Parameters.AddWithValue("@column", editedColumn);
            command.Parameters.AddWithValue("@value", value);
            command.Parameters.AddWithValue("@ID", IDtoUpdate);

            connection.Open();
            int rowsaffected = command.ExecuteNonQuery();

            MessageBox.Show("Rows affected: " + rowsaffected.ToString());

        }
    }

I don't think this works how you are anticipating, the query:

UPDATE ContactSet SET @column = @value WHERE Id = @ID

When executed does not do a 'string replacement' with your parameters, eg this does not translate to:

UPDATE ContactSet SET MyColumn = 1 WHERE Id = 789

Instead what is happening is you are update the SQL parameter @Column with the value of the parameter @Value if you find a matching row in the database where the Id = @ID.

You are getting '1 row affected' as there is a matching row in your update, but this is not actually changing anything within your contactset table.


You could do this like so:

public void UpdateContactInDB(int IDtoUpdate, string editedColumn, string value)
    {
        using (connection)
        {
            SqlCommand command = new SqlCommand(string.format(
                 "UPDATE ContactSet SET {0} = @value WHERE Id = @ID", 
                  editedColumn), connection);

            command.Parameters.AddWithValue("@value", value);
            command.Parameters.AddWithValue("@ID", IDtoUpdate);

            connection.Open();
            int rowsaffected = command.ExecuteNonQuery();

            MessageBox.Show("Rows affected: " + rowsaffected.ToString());

        }
    }

However you will need to be careful where the string values in editedColumn come from, as this would be open to SQL injection.

Better still to have an update that will update any of the columns you need to change, set all the appropriate parameters and you don't need dynamic SQL for this at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM