Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoted separator cursor copy_from in python

Is there any way to provide Quoted separator like

import psycopg2


f_cm = open('cm.sql', 'r')

constr = "dbname='mydb' user= 'pgsql' host='127.0.0.1'"
db = psycopg2.connect(constr)
st = db.cursor()

#st.copy_from(f_cm, 'mytable', sep='","', columns = ('col1','col2', 'col3'))
#instead of 
st.copy_from(f_cm, 'mytable', sep=',', columns = ('col1','col2', 'col3'))

Date format is:

"54654","4454","45465"
"54546","4545","885dds45"
"54536","4546","885dd45"

I have searched and found Good news at psycopg New in psycopg2.0.9

Go to heading What’s new in psycopg 2.0.9¶ which states: copy_from() and copy_to() can now use quoted separators.

tools:

psycopg2 = 2.4.5
python = 2.7.3
like image 1000
sharafjaffri Avatar asked Feb 16 '23 14:02

sharafjaffri


1 Answers

Seems Like cursor.copy_from or copy_to does not support Quoted sheets. solution is to use copy_expert.

import psycopg2


f_cm = open('cm.sql', 'r')

constr = "dbname='mydb' user= 'pgsql' host='127.0.0.1'"
db = psycopg2.connect(constr)
st = db.cursor()

copy = "COPY mytable(col1,col2, col3) FROM STDIN with csv"
st.copy_expert(sql=copy, file=f_cm)

db.commit()
st.close()
db.close()
like image 118
sharafjaffri Avatar answered Feb 18 '23 09:02

sharafjaffri