Baltimore snapped a six-game losing streak, a late-season skid that wiped out its hopes of making the playoffs.
The Orioles fell behind 3-0 in the early going, but Flaherty hit a two-run homer in the third that cut the Baltimore deficit to one. Steve Pearce tied the contest with a solo shot in the fourth and Flaherty scored the go-ahead run during a three-run fifth on a single by Nick Markakis.
Jonathan Schoop added a solo homer in the sixth for Baltimore and Flaherty tacked on another two-run blast in the eighth, giving him 10 for the season.
The victory ensured Baltimore will have a winning season.
T.J. McFarland (3-1) was credited with the win after throwing an inning in relief of Bud Norris. The final 2 1/3 innings were worked by Jason Hammel, who thus earned his first save of the year and the fourth of his career.
Esmil Rogers (5-9) endured the loss with a 4 1/3-inning effort in which he allowed six runs on eight hits.
Scarlett Johansson steps out with fiance after pregnancy reveal
Interpol investigating stolen passports on missing flight