简体   繁体   中英

Can you store bytes (Fernet token) in a MySQL table? python

I am trying to insert this Fernet encrypted token into my table in my database. It is encrypted Medical Information about a Scout

b'gAAAAABcIRmX3txIuOrw6FoSxy7I1vorA8hTTzMcXQGwch_jRBtWTsR9TwVyH125K0R6zG-BTvhv_SpZuW-Hs1WotaabBVj5tQ=='

By using this Insert statement

    sqlcommand = "INSERT INTO scoutinfo (scoutID, firstname,secondname,age,gender,ethnicity,address,postcode,medicalinfo,parentID,patrolID,userID) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
ScoutInput = (
    str(ScoutID), FName.get(), SName.get(), str(Age.get()), str(Gender.get()), str(Ethnicity.get()), Address.get(),
    Postcode.get(), EcryptMedInfo, str(ParentID[0]), str(PatrolID), str(UserID))
mycursor.execute(sqlcommand, ScoutInput)

Upon running, the program executes, however the insert is not applied to the table, and no, I have not forgotten about mydb.commit() . I believe that bytes is an unsupported datatype for MySQL and thus cannot be stored. I that case how would I overcome this, so that I will be able to decrypt the stored token by:

Ecy.decrypt(EcryptMedInfo)

If there is b"" and you want to transform it into string. You should use decode() instead of str() . Because it is difficult to reverse it if you used str() , but it will be easy if you use decode() .

a = b"\x00\x00"
print((a,a.decode(),str(a)))
print(a == a.decode().encode())
#(b'\x00\x00', '\x00\x00', "b'\\x00\\x00'")
#True

When i use mysql.connector , i don't have to transform them into string by myself.

import mysql.connector as mysql
from base64 import b64encode, b64decode
conn = mysql.connect(user="kr",passwd="kr",db="kr")
cur = conn.cursor()

def go(stat,param=None):
    try:
        cur.execute(stat,param)
        conn.commit()
    except Exception as e:
        conn.rollback()
        print(e)
go("""
    CREATE TABLE test(
    col varchar(90) NOT NULL
)""")
something = b64encode(b"\x00\x00")
print(something,type(something)) 
go(stat="""INSERT INTO test (col) VALUES (%s)""", param=[something])

cur.execute("SELECT col from test")
result = cur.fetchone()[0]
print([b64decode(result)])
#b'AAA=' <class 'bytes'>
#[b'\x00\x00']

I believe that bytes is an unsupported datatype for MySQL and thus cannot be stored.

Mysql can store it. Mysql byte array storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM