如何使用Python在MySQL中创建唯一ID字段

问题描述

如何在MysqL(SuiteCRM)中自动创建唯一ID字段?例如:“ e3df34-dg324g-sdsew23-dsdsw2”

python:

    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `accounts` (`id`,`name`) VALUES (%s,%s)"
            cursor.execute(sql,('sdi_234023','Alex'))

        connection.commit()
    finally:
        connection.close()

解决方法

您可以为它生成随机的uuid。使用以下代码。

    from uuid import uuid4
    try:
        with connection.cursor() as cursor:
            sql = "INSERT INTO `accounts` (`id`,`name`) VALUES (%s,%s)"
            cursor.execute(sql,(str(uuid4),'Alex'))

        connection.commit()
    finally:
        connection.close()