Home > Database > Mysql Tutorial > body text

How to write a Python CGI program to interact with MySQL?

WBOY
Release: 2023-09-17 21:01:02
forward
1355 people have browsed it

如何编写Python CGI程序与MySQL交互?

Assuming you want to use a Python CGi script to log into your account, here are 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>
Copy after login

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()
Copy after login

The above is the detailed content of How to write a Python CGI program to interact with MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!