Why does it hurt when you take sweets, if you have cavities in your teeth?
The outer shell of a tooth is enamel, which is hard and dense so that not much can penetrate it.  Under that is dentin (or dentine), which is bony but has microscopic channels running through it to the center of the tooth where the pulp and nerve reside.  If the enamel is breached, as with a cavity, crack, or wear, the dentin is exposed to the environment of the mouth.  When sugar comes against the dentin, it draws fluid out of the microscopic channels (because sugar attracts water strongly).  The fluid flow causes pressure changes around the nerve of the tooth, which reports the change to the brain where it registers as pain.  Dentin is highly sensitive not just to sugar, but also to hot, cold, pressure, and other stimuli.  (This sugar response is a short term one; the influence of sugar on bacteria is a longer-term effect in which the acid generated by the bacteria eats away the enamel layer.)