代码之家  ›  专栏  ›  技术社区  ›  Neel

从两个单独的列表创建erlang记录

  •  0
  • Neel  · 技术社区  · 7 年前

    在我们的一个erlang项目中,我们使用mysql otp从mysql数据库加载数据,如下所示-

    {ok, Columns, Rows} = mysql:query(ConnectionPid, <<"SELECT * FROM credentials WHERE username = ?">>, [Username])
    

    Columns Rows

    例如。

    Columns = [<<"id">>, <<"username">>, <<"password">>, <<"is_active">>]
    Rows = [[1,"test_user_1", "password", 'Y'], [2, "test_user_2", "password", 'Y']]
    

    现在,我们希望在加载时将mysql记录缓存到ets表中。因此,我们需要从上述两个列表中创建记录。

    例如,我们有以下记录声明

    -record(credentials, {id, username, password, is_active}).
    

    那么,如何创建 credentials 从以上两个列表中记录 和 排 . 有什么想法吗?

    我们不能使用 list_to_tuple 排 资格证书

    1 回复  |  直到 7 年前
        1
  •  0
  •   Pandemonium    7 年前

    如果你的数据 Rows 中的值的方式是一致的 [Id,Username,Password,IsActive|_] 可以始终被期望是有序的,其他额外的值将跟踪它们,您不需要 Columns

    以下是我如何理解列表:

    Creds = [ #credentials{
                     id=Id,
                     username=Usr,
                     password=Pw,
                     is_active=Act} || [Id,Usr,Pw,Act|_] <- Rows ]
    

    这个 _ 这意味着我们忽略了任何不适合我们的额外值 credentials 这是我的形状。