How does the submarine prevent water flow through the screw mechanism? The mechanism rotates the screw so there should be a little gap, how come the water doesn't come through this gap in to the submarine?
A variety of techniques are used for propeller shaft sealing. One of the most common is a "packing gland" or "stuffing box", as in illustration below from a dieselduck.info web page which has details of using such seals.
Also see boatus.com, which describes how much leakage to allow, and when to repack. Two or three drops of leakage per minute is recommended; the leakage helps lubricate the shaft where it passes through the seal. Leakage gets pumped out of the vessel as necessary. For some submarines, high leakage rates occur. For example, wikipedia notes that
Propeller shaft seals were a significant problem on Collins and Farncomb. Although designed to allow for a leak of 10 litres per hour, during trials it was found that the seals would regularly misalign and allow hundreds of litres per hour into the boat – during one deep diving test the flow rate was measured at approximately 1,000 litres a minute.