How to write Python CGI program to interact with MySQL?

suppose you want to login into you account using Python CGi script, below is the details

login.html


   
      
email: password:

login.py

#!C:\Python27\python.exe
import MySQLdb
import cgi
import Cookie

# Open database connection
db = MySQLdb.connect("localhost","root","","student" )

# prepare a cursor object using cursor() method
cursor = db.cursor()
data=cgi.FieldStorage()
a=data.getvalue('e1')
b=data.getvalue('p1')

# Prepare SQL query to fetch a record into the database.
sql = "select id,email,password from user where email='"+a+"' AND password='"+b+"'"
try:
# Execute the SQL command
if(cursor.execute(sql)): 
   # Commit your changes in the database 
   db.commit()
   c=Cookie.SimpleCookie()

   # assign a value
   c['mou']=a

   # set the xpires time
   c['mou']['expires']=24*60*60

   # print the header, starting with the cookie
   print c
   print("Content-type: text/html")
   print('''
      
         Hello Word - First CGI Program
      
      
         

successfully login

''') else: # Commit your changes in the database db.commit() print("Content-type: text/html") print("") print("") print("

fail

") print("") print("") except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
Updated on: 2019-07-30T22:30:22+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements