【问题标题】:Importing bytea data into PostgreSQL by using COPY FROM stdin使用 COPY FROM stdin 将 bytea 数据导入 PostgreSQL
【发布时间】:2017-06-26 07:56:15
【问题描述】:

我通过外部程序生成了一个 (UTF-8) 文件,用于导入 PostgreSQL 9.6.1。问题在于 bytea 字段 (PWHASH)。

来自该文件的片段(使用 TAB 作为分隔符)

COPY USERS (ID,CODE,PWHASH,EMAIL) FROM stdin;
7   test1   E'\\\\x657B954D27B4AC56FA997D24A5FF2563'    test@amce.org
\.

导入时

psql mydb myrole -f test.sql

一切顺利。

但是,如果我查询结果,字节数组不是16个字节,而是37个字节:

select passwordhash,length(passwordhash) from users;
                                 passwordhash                                 | length 
------------------------------------------------------------------------------+--------
 \x45275c78363537423935344432374234414335364641393937443234413546463235363327 |     37

正确的语法是什么?

【问题讨论】:

    标签: postgresql csv import


    【解决方案1】:

    输入文件的格式错误。应该是这样的:

    7   test1   \\x657B954D27B4AC56FA997D24A5FF2563 test@amce.org
    

    【讨论】:

    • 谢谢!但是,文档中在哪里提到了这种语法?我真的搜索了一些时间:(
    • 我是通过使用COPY ... TO 创建文件找到的。
    • 是的。这就是这样做的方法!再次感谢。
    【解决方案2】:

    我将不得不“准备”我相信的数据。喜欢这里:

    t=# insert into u select 'x657B954D27B4AC56FA997D24A5FF2563';
    INSERT 0 1
    Time: 5990.809 ms
    t=# select b from u;
                                      b
    ----------------------------------------------------------------------
     \x783635374239353444323742344143353646413939374432344135464632353633
    (1 row)
    
    Time: 0.234 ms
    t=# insert into u select  decode('657B954D27B4AC56FA997D24A5FF2563','hex');
    INSERT 0 1
    Time: 62.767 ms
    t=# select b from u;
                                      b
    ----------------------------------------------------------------------
     \x783635374239353444323742344143353646413939374432344135464632353633
     \x657b954d27b4ac56fa997d24a5ff2563
    (2 rows)
    
    Time: 0.208 ms
    

    所以在你的情况下,你可以:

    1. create table t as select ID,CODE,PWHASH::text,EMAIL from users where false;
    2. COPY t (ID,CODE,PWHASH,EMAIL) FROM stdin;
    3. insert into users select ID,CODE,decode(substr(PWHASH,4),'hex'),EMAIL from t;

    【讨论】:

    • 是的,我知道。但这不能在我的用例中使用,不是吗?
    猜你喜欢
    • 2022-07-21
    • 2019-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 1970-01-01
    • 2013-12-14
    相关资源
    最近更新 更多