原表裏面的數據沒有加密,建立了一張加密表,循環原表裏面的數據,加密後插入到加密表。最後建立一個觸發器,在原表裏面插入了數據,自動觸發在加密表裏面插入相同的數據。mysql
# _*_ coding: utf-8 _*_ __author__ = 'xiaoke' __date__ = '2018/6/12 18:25' """ 添加觸發器 CREATE TRIGGER `auth_enc_trigger` AFTER INSERT on auth FOR EACH ROW INSERT into `auth_enc` (id, real_name, id_number) VALUES (NEW.id,to_base64(aes_encrypt(NEW.real_name, "slwh-dfh")),to_base64(aes_encrypt(NEW.id_number, "slwh-dfh"))); 查詢加密後的表 select id,aes_decrypt(from_base64(real_name),'slwh-dfh'),aes_decrypt(from_base64(id_number),'slwh-dfh') from auth_enc; """ import MySQLdb db = MySQLdb.connect(host='localhost', port=3306, user='root', passwd='mypassword', db='my_db', charset='utf8') cursor = db.cursor() # 建立一個遊標對象 cursor.execute("select * from auth;") lines = cursor.fetchall() print("一共獲取數據%s條") % (len(lines)) for data in lines: id, real_name, id_number = data sql = 'insert into auth_enc (id, real_name, id_number) VALUE (%d,to_base64(aes_encrypt("%s","slwh-dfh")),to_base64(aes_encrypt("%s", "slwh-dfh")));' % ( id, real_name, id_number) print(sql) try: cursor.execute(sql) db.commit() except Exception, e: db.rollback() print(e) cursor.close()