如何在MySQL DB中使用UUID而不是整数

亚历克斯·丘比(Alex Chumbley)

我想使用python的uuid()函数来分配我的MySQL id,而不只是整数和AUTOINCREMENT

但是,如果uuid()在创建对象时生成了那也很好之前,我还没有广泛地使用SQL。因此,我能看到的唯一方法是在python代码中创建一个新对象,然后运行uuid()并手动对其进行手动分配,但这似乎是不必要的。

有没有办法将其集成到MySQL数据库中?

如果是这样,我应为该列分配什么数据类型?varchar?

发布者

MySQL没有真正的UUID支持-您可以将UUID存储在CHAR(32)列中,尽管您的索引可能不喜欢它。

SQLAlchemy文档提供了以下将Pythonuuid与任何数据库一起使用的方法

from sqlalchemy.types import TypeDecorator, CHAR
from sqlalchemy.dialects.postgresql import UUID
import uuid

class GUID(TypeDecorator):
    """Platform-independent GUID type.

    Uses Postgresql's UUID type, otherwise uses
    CHAR(32), storing as stringified hex values.

    """
    impl = CHAR

    def load_dialect_impl(self, dialect):
        if dialect.name == 'postgresql':
            return dialect.type_descriptor(UUID())
        else:
            return dialect.type_descriptor(CHAR(32))

    def process_bind_param(self, value, dialect):
        if value is None:
            return value
        elif dialect.name == 'postgresql':
            return str(value)
        else:
            if not isinstance(value, uuid.UUID):
                return "%.32x" % uuid.UUID(value)
            else:
                # hexstring
                return "%.32x" % value

    def process_result_value(self, value, dialect):
        if value is None:
            return value
        else:
            return uuid.UUID(value)

通过使用此代码段,您还将保持打开状态的可能性,以便以后切换到Postgres(确实具有本机UUID支持的数据库)

至于初始化对象:uuid.uuid4()创建新对象时,您可以分配一个新对象。数据库(尤其是不支持UUID的数据库)无法为您做到这一点。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章