Because 6 electron are present in the outermost shell of oxygen in order to get stability, oxygen gain or accept two electrons to attain noble gas electronic configuration for finding valency of oxygen
then the following formula is used for finding valency
8-valence electron = 0
8-6=2 that way valency of oxygen is 2
if you want to see more information about valency, click here
if you want to see more about valency of oxygen, click here