Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

วิธีเขียนโปรแกรม 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>

ไฟล์ login.py

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

# เปิดการเชื่อมต่อฐานข้อมูล
db = MySQLdb.connect("localhost","root","","student")

# เตรียม cursor object
cursor = db.cursor()

data = cgi.FieldStorage()
a = data.getvalue('e1')
b = data.getvalue('p1')

# เตรียมคำสั่ง SQL เพื่อดึงข้อมูล
sql = "select id,email,password from user where email='"+a+"' AND password='"+b+"'"

try:
    # รันคำสั่ง SQL
    if(cursor.execute(sql)):
        # Commit การเปลี่ยนแปลง
        db.commit()
        c = Cookie.SimpleCookie()
        # กำหนดค่า
        c['mou'] = a
        # กำหนดเวลาหมดอายุ
        c['mou']['expires'] = 24*60*60
        # พิมพ์ header เริ่มจาก 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:
        db.commit()
        print("Content-type: text/html")
        print("<html>")
        print("<body>")
        print("<h2>fail</h2>")
        print("</body>")
        print("</html>")
except:
    # Rollback หากมีข้อผิดพลาด
    db.rollback()
    # ตัดการเชื่อมต่อ
    db.close()

หมายเหตุ: โค้ดตัวอย่างนี้ใช้ Python 2.7 และ MySQLdb สำหรับ Python 3 ควรใช้ PyMySQL หรือ mysql-connector-python แทน และควรใช้ Parameterized Query เพื่อป้องกัน SQL Injection