我在使用 Python 脚本时遇到问题,无论我给脚本提供什么参数,它都不会执行 if 分支。我的代码有问题吗?我正在执行一个 HTML 表单,结果没问题,直到我向 else 语句添加了一些内容......我已经尝试了一切,但它仍然不想工作......
#!/usr/bin/python3
import pymysql
import cgi
from http import cookies
# Open database connection
db = pymysql.connect("localhost","superadmin","123","dinamic" )
# 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 register WHERE email = %s AND password = %s"
try:
# Execute the SQL command
cursor.execute(sql, (a, b))
# Commit your changes in the database
db.commit()
c=cookies.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", end="\r\n\r\n", flush=True);
print('''<html><head><title>First python script for Security and Encrpytion class</title></head><body><center><h2>Successfully login!</h2><br><img src='image/2.gif'></body></html>''');
except:
db.commit()
print("Content-type: text/html", end="\r\n\r\n", flush=True);
print("<html>");
print("<body>");
print("<center>")
print("<h2>Fail to login!</h2>");
print("<img src='image/dinamic.gif'>");
print("</body>");
print("</html>");
# Rollback in case there is any error
db.rollback()
答案 0 :(得分:1)
cursor.execute()
不返回选择的行数。您可以调用 cursor.fetchone()
来查看它是否返回一行。
也无需调用 db.commit()
,因为您还没有进行任何更改。
try:
# Execute the SQL command
cursor.execute(sql, (a, b)))
row = cursor.fetchone()
if row:
c=cookies.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", end="\r\n\r\n", flush=True);
print("");
print('''<html><head><title>Security & Encryption class - First script</title></head><body><h2>successfully login!</h2>''');
print("<center>");
print("<img src='image/successfully.gif'>");
print("</center>");
print("</body></html>");
else:
print ("Content-type: text/html", end="\r\n\r\n", flush=True)
print("<html>")
print("<body>")
print("<center>")
print("<h2>Login fail!</h2>")
print("<img src='image/dinamic.gif'>")
print("<br><br>")
print('<button id="myButton" class="float-left submit-button" >Home</button>')
print('''<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "index.html";
};
</script>''');
print("</center>");
print("</body>");
print("</html>");
except:
# Rollback in case there is any error
db.rollback()