My Schema
Table Articles
id -> AUTO_INCREMENT
article_name -> STRING
hash_id -> STRING
这是我的代码,Python
cursor.execute("Insert into articles(id,article_name) values (NULL,'Harry Potter')")
id = cursor.lastrowid # Gets the AUTO_INCRENT value
hash_id = hash_id_function(id) # converts INT to Non-Sequential eg. '112' -> '23jk32j'
cursor.execute("UPDATE Articles set hash_id='23jk32j' where id='112'")
每当发生读取时,我希望 ROW 包含哈希 (以上 2 个查询必须已完全执行(
考虑到MySQL(Innodb(必须等待我的pythonic hash_id_function
执行,我如何使用事务来实现这一点?
最好的解决方案是使用触发器。要实现这一点,您必须将hash_id_function()
转换为mysql函数,或者使用mysql中的内置函数之一。
通过执行以下示例查询之一来安装触发器一次,在将来的插入中,它将自动执行。
此示例触发器使用 SHA2()
来构建哈希,您可以使用MD5()
:
delimiter //
drop trigger if exists tg_bi_articles //
create trigger tg_bi_articles before insert on articles
for each row begin
set new.hash_id = (
SELECT SHA2(AUTO_INCREMENT,0)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='articles'
AND TABLE_SCHEMA=DATABASE());
end;
//
delimiter ;
如果你不需要这样的安全哈希,你可以从哈希中获取前几个字符:
delimiter //
drop trigger if exists tg_bi_articles //
create trigger tg_bi_articles before insert on articles
for each row begin
set new.hash_id = (
SELECT LEFT(MD5(AUTO_INCREMENT),5)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='articles'
AND TABLE_SCHEMA=DATABASE());
end;
//
delimiter ;
如果您需要能够解密的哈希,则可以使用AES_ENCRYPT
delimiter //
drop trigger if exists tg_bi_articles //
create trigger tg_bi_articles before insert on articles
for each row begin
set new.hash_id = (
SELECT AES_ENCRYPT(AUTO_INCREMENT,UNHEX('FA32C2E389AB50213F530C0CA1A390C3'))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME='articles'
AND TABLE_SCHEMA=DATABASE());
end;
//
delimiter ;
最后一个选项是将您的函数转换为 SQL 函数并将其添加到触发器中,但无论您做什么触发器都会为您带来魔力:)因为现在当你做以下插入
cursor.execute("Insert into articles(id,article_name) values (NULL,'Harry Potter')")
那么这就是您将在数据库中找到的内容(使用第二个示例触发器时(:
( 3, 'Harry Potter', 'eccbc' )
希望这有帮助
关键是在连接器/Python 中使用 MySQL 事务
cnx.autocommit = False # Sets Autocommit to False,
cursor.execute(Insert_Query)
id = cursor.lastrowid; #Get Last Autoincrement value
hash_id = hash_id_function(id)
cursor.execute("UPDATE Table set hash_id=...")# Run the Update Query
cnx.commit() # Commit your changes,
except ValueError as err:
cnx.rollback() # If something happens Rollback (UNDO the changes)
这将确保整个表的完整性
了解有关 MySQL 中的事务的更多信息