I’m currently writing a class to handle all database-activity in my application, and so I’ve come to the method that performs UPDATE-queries.
As of now I’m returning and displaying the content of the commandtext to check it, and it seems fine:
UPDATE news SET title = @title, newsContent = @newsContent, excerpt = @excerpt, date = @date, urlTitle = @urlTitle, isPublished = @isPublished WHERE (id = @id);
So, fine in other words. The next step is to replace all @values with actual values – and this is where i hit problems. Nothing happens. The AddWithValue-method just doesn’t seem to do anything, and i find no reason for this.
public string updateQuery(string table, string[] fields, object[] values, string conditionField, object conditionValue) { try { StringBuilder cmd = new StringBuilder('UPDATE ' + table + ' SET '); int i = 1; foreach (string s in fields) { if (i == fields.Length) { cmd.Append(s + ' = @' + s + ' '); } else { cmd.Append(s + ' = @' + s + ', '); } i++; } cmd.Append('WHERE (' + conditionField + ' = @' + conditionField + ');'); command.CommandText = cmd.ToString(); int j = 0; foreach (object o in values) { command.Parameters.AddWithValue('@' + fields[j], o); j++; } command.Parameters.AddWithValue('@' + conditionField, conditionValue); command.ExecuteNonQuery(); connection.Close(); return command.CommandText; } catch (Exception ex) { throw ex; } }
Anyone?
Thanks for the suggestions Joel Coehoorn, i will look into them.
Still, i want to get my stuff to work :p
Just noticed that the date-field actually have been updating itself all the time. None of the other fields, though. This just makes less sense the more i look at it. Maybe its better to try in the morning than at midnight.
EDIT: Found out what the problem was, and it was far simpler than i expected. I’d forgotten to check if the page was a postback, so every time i updated the database, the fields were filled with data FROM the database before the submit-method was called. So, the update-method worked all along. blush