Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting rows into db from a list of tuples using cursor.mogrify gives error

I am trying to insert large number of rows into postgres using cursor.mogrify using this psycopg2: insert multiple rows with one query

data is a list of tuples where each tuple is a row that needs to be inserted.

 cursor = conn.cursor()

    args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)

    cursor.execute(
        "insert into table1 (n, p, r, c, date, p1, a, id) values " + args_str)`

but getting error :

TypeError: sequence item 0: expected str instance, bytes found

at line:

  args_str = ','.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data)

If I try to change to b''.join(cursor.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in data) , then execute query gives error for inserting byte....

Am I doing something wrong ?

like image 336
MANU Avatar asked Jan 24 '26 16:01

MANU


1 Answers

data = [(1,2),(3,4)]
args_str = ','.join(['%s'] * len(data))
sql = "insert into t (a, b) values {}".format(args_str)
print (cursor.mogrify(sql, data).decode('utf8'))
#cursor.execute(sql, data)

Output:

insert into t (a, b) values (1, 2),(3, 4)
like image 53
Clodoaldo Neto Avatar answered Jan 27 '26 08:01

Clodoaldo Neto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!