把csv文件到postgresql中时,能否有选择几列导入?使用copy语句

解决方案 »

  1.   

    看我的试验。对列进行not null 约束
    postgres=# create table t(id int not null, username char(20) not null);
    CREATE TABLE
    postgres=# insert into t values (1,'wenwen'),(2,'shushu'),(4,'ss');
    INSERT 0 3
    postgres=# select * from t;
      1 | wenwen              
      2 | shushu              
      4 | ss                  
    postgres=# copy t to '/tmp/t.txt' with csv;
    COPY 3
    postgres=# delete from t;
    DELETE 3
    postgres=# copy t(id) from '/tmp/t.txt';
    ERROR:  invalid input syntax for integer: "1,wenwen              "
    CONTEXT:  COPY t, line 1, column id: "1,wenwen              "
    postgres=# copy t(id) from '/tmp/t.txt' with csv;
    ERROR:  extra data after last expected column
    CONTEXT:  COPY t, line 1: "1,wenwen              "
    postgres=# copy t from '/tmp/t.txt' with csv;
    COPY 3
    postgres=# select * from t;
      1 | wenwen              
      2 | shushu              
      4 | ss                  postgres=# copy t(id) to '/tmp/t.txt' with csv;
    COPY 3
    postgres=# delete from t;
    DELETE 3
    postgres=# copy t(id) from '/tmp/t.txt' with csv;
    ERROR:  null value in column "username" violates not-null constraint
    CONTEXT:  COPY t, line 1: "1"
    去掉not null 约束
    postgres=# drop table t;
    DROP TABLE
    postgres=# create table t (id int,username char(20));
    CREATE TABLE
    postgres=# copy t(id) from '/tmp/t.txt' with csv;
    COPY 3
    postgres=# select * from t;
      1 | 
      2 | 
      4 | postgres=#