代码之家  ›  专栏  ›  技术社区  ›  as - if

将数据帧复制到具有defalut值的列的postgres表

  •  1
  • as - if  · 技术社区  · 6 年前

    我有下面的postgreSql表 stock ,结构如下 insert_time 具有默认值 now()

    |    column   |  pk |    type   |
    +-------------+-----+-----------+
    | id          | yes | int       |
    | type        | yes | enum      |
    | c_date      |     | date      |
    | qty         |     | int       |
    | insert_time |     | timestamp |
    

    我在试着 copy 以下 df

    |  id | type |    date    | qty  |
    +-----+------+------------+------+
    | 001 | CB04 | 2015-01-01 |  700 |
    | 155 | AB01 | 2015-01-01 |  500 |
    | 300 | AB01 | 2015-01-01 | 1500 |
    

    我在用 psycopg 上传 数据框 上桌 股票

    cur.copy_from(df, stock, null='', sep=',')
    conn.commit()
    

    得到这个错误。

    DataError: missing data for column "insert_time"
    CONTEXT:  COPY stock, line 1: "001,CB04,2015-01-01,700"
    

    我期望使用psycopg copy_from函数,我的postgresql表将自动填充插入时间旁边的行。

    |  id | type |    date    | qty  |     insert_time     |
    +-----+------+------------+------+---------------------+
    | 001 | CB04 | 2015-01-01 |  700 | 2018-07-25 12:00:00 |
    | 155 | AB01 | 2015-01-01 |  500 | 2018-07-25 12:00:00 |
    | 300 | AB01 | 2015-01-01 | 1500 | 2018-07-25 12:00:00 |
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Peter Majko    6 年前

    可以指定如下列:

    cur.copy_from(df, stock, null='', sep=',', columns=('id', 'type', 'c_date', 'qty'))