Cain (2-2) was effective on the mound, limiting the Diamondbacks to one run on three hits while walking two.
He also was valuable at the plate, delivering two key RBI in the sixth inning that put San Francisco ahead 4-1.
Three Giants relievers combined to hold Arizona to one unearned run over 1 2/3 innings and Santiago Casilla wrapped up the win with a scoreless ninth as San Francisco evened its three-game road series.
Melky Cabrera went 3-for-5 with a two-run double for the victors.
D-Backs starter Trevor Cahill (2-4) was tagged for four runs on six hits in a 5 2/3-inning effort.
Willie Bloomquist got Arizona's only RBI.
Benedict Cumberbatch's dramatic reading of R. Kelly lyrics is just what you need
Jordana Brewster on Paul Walker: 'He was an enormous presence in my life'