首页 > 数据库 > mysql教程 > 如何编写Python CGI程序与MySQL交互?

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

WBOY
发布: 2023-09-17 21:01:02
转载
1404 人浏览过

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

假设您想使用Python CGi脚本登录您的帐户,以下是详细信息

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>
登录后复制

登录.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()
登录后复制

以上是如何编写Python CGI程序与MySQL交互?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板