"I am not getting the proper output."
It'd be helpful if you told us what output you do get. How do I post a question effectively?. Also you posted this question in the wrong section of the forum, again. Where should I post X?.
"Where am I going wrong? Please help."
You don't seem to be making an effort at debugging your code, some simple print statements would help you track down at which point you are going wrong. Basic debugging checklist, Debugging and Optimization, tutorials.
Update: are you also prithviraj who posted SQL Database Table to Perl Script?