0
import csv
import psycopg2
conn = psycopg2.connect(database=" ", user=" ", password=" ", host=" ", port= )

cur = conn.cursor()
with open('21.csv', 'r') as f:
       next(f)
       cur.copy_from(f, 'temp_questions', sep=',')
                
conn.commit()

i have try to insert data into my db i got error:

cur.copy_from(f, 'temp_questions', sep=',')
psycopg2.errors.QueryCanceled: COPY from stdin failed: error in .read() call: exceptions.ValueError Mixing iteration and read methods would lose data

CONTEXT: COPY temp_questions, line 1

in my csv file -i have 18 column and table(database)- id with 18 column i don't know how to insert data

7
  • cur.copy_from(f, 'temp_questions', sep=',',columns=['question', 'choice_a', 'choice_a_media_url', 'choice_b', 'choice_b_media_url', 'choice_c', 'choice_c_media_url', 'choice_d','choice_d_media_url','choice_e','choice_e_media_url','answer','ctime','utime','question_media_url','status','qtype','wiki_url']) i change code added column name(table column) but same error Commented Aug 20, 2021 at 9:25
  • cdn.riddle.com/embeds/v2/images/q_80,c_fill,w_960,h_540/d64/… this is my image url Commented Aug 20, 2021 at 10:19
  • here also having semicolon i want to remove this how to do? Commented Aug 20, 2021 at 10:20
  • or any other method to solve the problem plz help me to find solution Commented Aug 20, 2021 at 10:20
  • always put code, data and full error message as text (not screenshot, not link) in question (not in comment). Commented Aug 20, 2021 at 11:33

1 Answer 1

0
import csv
db=conn.connect('test.db')
print("connected succesfully")
csv_file="test.csv"
with open(csv_file,'r') as csv_file:
    csvreader=csv.reader(csv_file)
    fields=next(csvreader)
    sql_insert_query='INSERT INTO Test (name,age) VALUES(?,?)'
    db.executemany(sql_insert_query, csvreader)
    print("inserted")
data=db.execute("SELECT * FROM Test")
for i in data:
    print(i)

Read the data from csv file and use executemany to insert an array of elements to the database.

Sign up to request clarification or add additional context in comments.

1 Comment

Three things wrong with this answer: 1) If the CSV file is of any size executemany() will take a long time. See Cursor 2) In psycopg2 the parameter placeholder is %s not ?. See Parameters 3) psycopg2 has COPY support. See Copy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.