![](/img/trans.png)
[英]Hi can someone please help me. i don't know what the problem is and I'm new to coding. im using python and im trying to create a class Student
[英]Hi, I'm new to SQL/python, could someone please help me with searching databases using python commands, thanks :)
我有一個名為“ staff”的表,其中有幾列,但是我感興趣的兩列是“ username”和“ password”。 我正在嘗試創建一個提示,詢問用戶其用戶名(稍后我將輸入密碼)並檢查數據庫中的表以查看該用戶名是否存在。 我對如何執行此操作一無所知,但這是我到目前為止編寫的代碼。 如果有人可以提供幫助,將不勝感激,謝謝。
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="sakila")
cur = db.cursor()
search = raw_input("Enter username: ")
query = ('SELECT username, password FROM staff')
cur.execute(query)
results = cur.fetchall()
if search in results:
print("username found")
else:
print("invalid username")
db.close()
編輯:確保從底部的@FallenAngel檢查注釋,並檢查代碼中的安全風險!
正如戈登提到的那樣,您應該使用WHERE
子句使事情變得更容易。 像這樣:
import re
import MySQLdb
db = MySQLdb.connect(host="127.0.0.1", user="root", passwd="", db="sakila")
cur = db.cursor()
search = raw_input("Enter username: ")
user_regex = # input a regex here to make sure the username matches a format which avoids SQL injection.
if re.search(user_regex, search):
query = ("SELECT password FROM staff WHERE username = %s", (search,)) # add a WHERE clause
cur.execute(query)
results = cur.fetchall()
else:
results = None
if results: # Now we just need to check if the queryset is empty or not.
print("username found")
else:
print("invalid username")
db.close()
一般經驗法則是嘗試使SQL
進行搜索,它是為此而構建的,因此將比Python
更快。
確保您的用戶名列是主鍵(或至少是唯一鍵),這樣您就不會重復。
編輯:基於@FallenAngels點,您不應直接將用戶輸入注入SQL查詢,因為它將使您暴露於SQL注入。
編輯2:
首先請注意,此解決方案不安全,因此我們不再使用"%s" % var
格式! 相反,我們使用的是用於db queries
“%s”(var)格式。
string
中的%s
(也可以是%d
, %n
和其他幾個字母)是一種string formatting
用於將可變內容插入到string
。
本質上,如果您說:
"some stuff here: %s" % var
var中的所有內容都將替換字符串中的%s
。 有很多復雜的地方,因此值得在這里閱讀更多內容: https : //docs.python.org/2/library/string.html
也許您需要將其分發到兩個文件中
在第一個文件中,請構建表單,然后通過app.route將其鏈接到python文件中的def。
這樣,您可以將演示文稿和業務模型完全分開,並且也將保持更高的可維護性。
請讓我知道您是否需要簡化代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.