Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COPY NULL values in Postgresql using psycopg2 copy_from()

This seems like a rather popular question, but all the answers around here did not help me solve the issue... I have a Postgresql 9.5 table on my OS X machine:

CREATE TABLE test (col1 TEXT, col2 INT)

The following function uses the psycopg2 copy_from() command:

def test_copy(conn, curs, data):
    cpy = BytesIO()
    for row in data:
         cpy.write('\t'.join([str(x) for x in row]) + '\n')
    print cpy
    cpy.seek(0)
    curs.copy_from(cpy, 'test')

test_copy(connection, [('a', None), ('b', None)])

And will result in this error:

ERROR:  invalid input syntax for integer: "None"
CONTEXT:  COPY test, line 1, column col2: "None"
STATEMENT:  COPY test FROM stdin WITH DELIMITER AS '    ' NULL AS '\N'

I tried also curs.copy_from(cpy, 'test', null=''), curs.copy_from(cpy, 'test', null='NULL'). Any suggestions are greatly appreciated.

like image 521
n1000 Avatar asked Feb 10 '16 11:02

n1000


1 Answers

OK, after more trial & error I found the solution:

copy_from(cpy, 'test', null='None')
like image 142
n1000 Avatar answered Nov 03 '22 18:11

n1000