
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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
<html> <body> <form action="login.py" method="get"> email: <input type="text" name="e1"> password: <input type="password" name="p1"> <input type="submit" value="register"> </form> </body> </html>
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('''<html> <head> <title>Hello Word - First CGI Program</title> </head> <body> <h2>successfully login</h2> </body> </html>''') else: # Commit your changes in the database db.commit() print("Content-type: text/html") print("<html>") print("<body>") print("<h2>fail</h2>") print("</body>") print("</html>") except: # Rollback in case there is any error db.rollback() # disconnect from server db.close()
- Related Articles
- How to write first Hello World program using CGI programming in Python?
- What Content-type is required to write Python CGI program?
- Passing Checkbox Data to CGI Program in Python
- How to interact with your audience on YouTube?
- Passing Radio Button Data to CGI Program in Python
- Passing Text Area Data to CGI Program in Python
- First CGI Program in Python
- How to interact with hidden elements in Selenium Webdriver?
- How to do CGI programming in Python?
- Passing Drop Down Box Data to CGI Program in Python
- How to setup cookies in Python CGI Programming?
- How to retrieve cookies in Python CGI Programming?
- How to configure Apache for Python CGI Programming?
- How to pass Radio Button Data to Python CGI script?
- How to pass Text Area Data to Python CGI script?

Advertisements