MIAMI — NL hits leader Casey McGehee homered for the second time this season, and the Miami Marlins took the lead for good on a wild pitch by Tim Lincecum in the seventh inning to beat the San Francisco Giants 3-2 Sunday.

Miami stopped a six-game losing streak and averted a three-game series sweep.

McGehee came in with 118 hits and 54 RBIs, and the two-run homer in the first inning was his first since May 10. Lincecum (9-6) allowed three runs in seven innings, ending his streak of wins in four consecutive starts.

Brad Hand (1-2) gave the Marlins' shaky rotation a welcome boost by pitching seven innings to match a career high, and he allowed two runs. He had been 1-12 previously as a starter, with the lone victory in 2011.

Hand lowered his ERA to 5.02 in six starts this year. Steve Cishek pitched a perfect ninth for his 21st save in 24 chances.

With the score 2-all, Adeiny Hechavarria doubled to start Miami's seventh, took third on a sacrifice and came home when Lincecum bounced a curve to Reid Johnson, and the ball caromed away from catcher Hector Sanchez.

McGehee had two hits to hike his average to .322. He also made a barehanded grab and throw at third base to rob Buster Posey of a hit in the eighth.

The Giants' offense, which has sputtered for much of July, suffered a relapse after three consecutive robust games. Posey drove in their runs with a double in the third.

Miami won with only six hits and despite a succession of basepath blunders. The Marlins had three runners tagged out between second and third in the first three innings.