I'm using Python 3
and mysql.connector
module. I could not store the hased password to the database.
Here is my code:
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()
When I run the INSERT
statement, the error occurred:
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
Noted: My datatype for password
is CHAR(96)
I appreciate your help.
CodePudding user response:
Use query parameters instead of string-formatting.
// WRONG
self.cursor.execute("INSERT INTO test (password) VALUE ('%s')" % (hash_pass))
// RIGHT
self.cursor.execute("INSERT INTO test (password) VALUE (%s)", (hash_pass,))
Both methods use %s
as a placeholder, which is kind of confusing because it looks like it's doing the same thing. But the latter is not doing simple string substitution. It makes the value safe for the SQL query, either by escaping special characters, or by doing true query parameters, keeping the value separate until after the query has been parsed.