November 13, 2007

C# SQL Update Key Value Type Table

// Updates a table called databaseTableName with columns 
// 'Key' and 'Value'. Its untested!
public void UpdateSettingValueEntry(
  string databaseTableName, string key, string value)
{
  private const string updateCommand = 
   "UPDATE {0} SET Value = @value WHERE Key = '{1}'"
  using (SqlConnection databaseConnection = 
         new SqlConnection(DatabaseConnectionString))
  {
    try
    {
      databaseConnection.Open();

      using (SqlCommand command = new SqlCommand())
      {
        command.Connection = databaseConnection;
        command.CommandText = string.format(updateCommand, 
              databaseTableName, key);
        command.Parameters.AddWithValue("@value", value);
        Debug.Trace("SQL({0})", command.CommandText);
        int rows = command.ExecuteNonQuery();
        if (rows == 1)
        {
           Debug.WriteLine("Updated key \'" + key + 
              "\' to value of \'" +
               value + "\'");
        }
        else
        {
          HandleError("Updated key \'" + key + 
           "\' to value of \'" + value + 
           "\' returned unexpected row count of \'" +
           rows + "\'");
        }
        if (rows < 1)
        {
          HandleUpdateError(xxx);
        }
      }
    }
    catch (SqlException se)
    {
      HandleException(se);
    }
  }
}

No comments: