Python Psycopg2 – 一次查询插入多行
这篇文章是关于用一个查询在我们的指定数据库的表中插入多行。有多种方法可以执行此任务,让我们看看我们如何从以下方法中完成它。
方法一:通过 Naive 方法插入值
在此方法中,我们导入 psycopg2 包并使用 psycopg2.connect() 方法形成连接,我们连接到“教室”数据库。建立连接后,我们使用 connect().cursor() 方法创建一个游标,它将帮助我们获取行。之后我们执行插入 SQL 语句,格式如下:
insert into table_name ( column1, column2, …. column_n) values (…) (…) (…) ;
SQL 语句由 cursor.execute() 方法执行。我们使用 cursor.fetchall() 方法获取行。
使用的 CSV:
例子:
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# sql statement to be executed
sql = '''insert into classroom(enrollment_no, name , science_marks)
values(12, 'sarah', 90),(13,'Ray',81); '''
# executing the sql statement
cursor.execute(sql)
# select statement to display output
sql1 = '''select * from classroom;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# committing changes
conn.commit()
# closing connection
conn.close()
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
values = [(14, 'Ian', 78), (15, 'John', 88), (16, 'Peter', 92)]
# cursor.mogrify() to insert multiple values
args = ','.join(cursor.mogrify("(%s,%s,%s)", i).decode('utf-8')
for i in values)
# executing the sql statement
cursor.execute("INSERT INTO classroom VALUES " + (args))
# select statement to display output
sql1 = '''select * from classroom;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# commiting changes
conn.commit()
# closing connection
conn.close()
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
values = [(17, 'rachel', 67), (18, 'ross', 79), (19, 'nick', 95)]
# executing the sql statement
cursor.executemany("INSERT INTO classroom VALUES(%s,%s,%s)", values)
# select statement to display output
sql1 = '''select * from classroom;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# commiting changes
conn.commit()
# closing connection
conn.close()
输出:
Python中的输出:
(4, 'Linnett', 79)
(5, 'Jayden', 45)
(6, 'Sam', 63)
(7, 'Zooey', 82)
(8, 'Robb', 97)
(9, 'Jon', 38)
(10, 'Sansa', 54)
(11, 'Arya', 78)
(12, 'sarah', 90)
(13, 'Ray', 81)
方法 2:通过 cursor.mogrify() 插入值
代码与前面的示例相同,但不同之处在于 cursor.mogrify() 方法。
cursor.mogrify() 方法:
绑定参数后,返回一个查询字符串。如果您使用 execute() 方法或类似方法,返回的字符串与发送到数据库的字符串相同。返回的字符串始终是字节字符串,这比 executemany() 方法快。
句法:
cur.mogrify(“INSERT INTO test (col) VALUES (%s, %s….)”, (val1, val2,…)(……))
cursor.mogrify() 返回一个字节字符串,但我们希望它是字符串格式,因此我们只需使用 decode('utf-8') hack 将 mogrify 的结果解码回字符串。
例子:
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
values = [(14, 'Ian', 78), (15, 'John', 88), (16, 'Peter', 92)]
# cursor.mogrify() to insert multiple values
args = ','.join(cursor.mogrify("(%s,%s,%s)", i).decode('utf-8')
for i in values)
# executing the sql statement
cursor.execute("INSERT INTO classroom VALUES " + (args))
# select statement to display output
sql1 = '''select * from classroom;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# commiting changes
conn.commit()
# closing connection
conn.close()
输出:
方法 3:通过 executemany() 方法插入值
此示例的方法与之前相同,但我们使用 cursor.executemany() 方法来代替 cursor.mogrify()。与 mogrify() 方法相比,executemany() 速度较慢。
执行许多():
它用于将数据库操作(查询或命令)应用于 vars 列表序列中的所有参数元组或映射。该函数对于数据库更新指令特别有用,因为它会丢弃查询产生的任何结果集。查询的参数使用与 execute()函数相同的原理进行绑定。
句法
executemany(query, variable_list)
例子:
Python3
# importing packages
import psycopg2
# forming connection
conn = psycopg2.connect(
database="Classroom",
user='postgres',
password='pass',
host='127.0.0.1',
port='5432'
)
conn.autocommit = True
# creating a cursor
cursor = conn.cursor()
# list of rows to be inserted
values = [(17, 'rachel', 67), (18, 'ross', 79), (19, 'nick', 95)]
# executing the sql statement
cursor.executemany("INSERT INTO classroom VALUES(%s,%s,%s)", values)
# select statement to display output
sql1 = '''select * from classroom;'''
# executing sql statement
cursor.execute(sql1)
# fetching rows
for i in cursor.fetchall():
print(i)
# commiting changes
conn.commit()
# closing connection
conn.close()
输出: