Cain (1-2) held the Dodgers to one run over 7 1/3 innings in logging his initial victory after seven winless starts to begin the season. The right-hander allowed five hits and three walks while striking out four.
Sergio Romo was called on to make his 12th save with a 1-2-3 ninth after the Dodgers narrowed the Giants' 4-0 lead with three runs in the eighth.
Hunter Pence drove in all four San Francisco runs with a pair of doubles and an RBI groundout as the Giants took three straight from their California rivals notched a sixth consecutive win overall.
Dodgers starter Hyun-Jin Ryu (3-2) absorbed the loss, surrendering four runs on eight hits over six innings.
Adrian Gonzalez drove in two runs for fourth-place Los Angeles, which fell 5 1/2 games behind the National League West-leading Giants.
Celebrity Families of 2014 [PHOTOS]