我正在使用Python 3和mysql.connector模塊。我無法將 hased 密碼存盤到資料庫中。
這是我的代碼:
import bcrypt
import base64, hashlib
import mysql.connector
class test:
def __init__(self):
self.cnx = mysql.connector.connect(**Connect)
self.cursor = self.cnx.cursor()
pw = "Test123!"
password=pw.encode('utf-8')
hash_pass = bcrypt.hashpw(base64.b64encode(hashlib.sha256(password).digest()),bcrypt.gensalt())
print(hash_pass)
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
self.cnx.commit()
test()
當我運行該INSERT陳述句時,發生了錯誤:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '$2b$12$2Jo8.yam0VU5IKQxMa4EV.ReuFGeG43wmzbrFDsT5Pr5c8L2rmlP6'')' at line 1
注意:我的資料型別password是CHAR(96)
我感謝您的幫助。
uj5u.com熱心網友回復:
使用查詢引數而不是字串格式。
// WRONG
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
// RIGHT
self.cursor.execute("INSERT INTO test (password) VALUE (%s)", (hash_pass,))
這兩種方法都%s用作占位符,這有點令人困惑,因為它看起來像是在做同樣的事情。但后者不是在做簡單的字串替換。它使 SQL 查詢的值安全,或者通過轉義特殊字符,或者通過執行真正的查詢引數,在決議查詢之前保持值分開。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/438134.html
標籤:Python mysql bcrypt 密码加密 密码哈希
下一篇:SQL-如何在案例中加入
