The reason why your stomach hurts so bad after eating beans is because beans contain a sugar called oligosaccharides that the body cannot easily digest.
Because your body is having trouble digesting the oligosaccharides it can lead to fermentation by bacteria in your large intestine which leads to gas and bloating and also cause stomach pain and stomach discomfort.
Essentially when you eat beans and can't digest them or their sugars properly, your gut bacteria are feeding on the beans sugars which are undigested and creates gas a byproduct.
Beans are also high in fiber that can be difficult for some people to digest and also lead to bloating, stomach pain and discomfort.
Beans also contain a carbohydrate called Raffinose that is also hard to digest by the human body and is a major cause of gas production in the body.
To reduce stomach pain and gas and bloating from the beans you should soak the beans overnight in water which breaks down some of the complex sugars.
You can also cook the beans with some Kombu which is a type of seaweed that can be added to the beans while cooking or eat smaller portions of beans to reduce gas.
To neutralize gas after eating beans you can take some Beano or other gas reducing supplements or drink plenty of water which aids in digestion and reduces bloating.
You can put baking soda in beans when cooking them to prevent gas.