Henriette Reker, an independent close to Merkel's ruling Christian Democrats (CDU), suffered serious wounds to the neck in the attack in the western city of Cologne, which is to elect its mayor on Sunday.
Police arrested the attacker at the scene, with regional police chief Wolfgang Albers describing it as a "political act" linked to the fact that Reker was "responsible for taking charge of refugees" in the city, the fourth largest in Germany.
The attacker, a 44-year-old unemployed man, "said he had a racist motivation for committing this act," Cologne police official Norbert Wagner told a news conference.
Merkel "expressed her shock and condemned this act," a spokesperson told AFP, while Interior Minister Thomas de Maziere called it an "appalling, cowardly" attack.
The violence took place as Germany struggles with a huge influx of Syrian asylum seekers, whose numbers are expected to reach between 800,000 and a million by the end of the year.
The chancellor's open-door policy has provoked a backlash among her conservative allies and sparked protests among the far-right.
Reker is seen as standing a good chance of securing the mayorship Sunday in Cologne, Germany's fourth-largest city with 980,000 inhabitants.
