我想在PostgreSQL表中插入多行。我附上了这个程序。我使用了一个项目列表:new_record = [' one',' two'' three']。 实际上,这个列表将填充来自亚马逊产品的100000个项目,但现在我填写了3个项目。我创建一个for循环迭代,但它只填充一个元素。 我想打印所有项目。例如:
"INSERT INTO products(products_amazon) VALUES ('one')"
"INSERT INTO products(products_amazon) VALUES ('two')"
"INSERT INTO products(products_amazon) VALUES ('three')"
我将不胜感激。
import psycopg2
from pprint import pprint
database = "amazon_products"
host = "localhost"
user = "postgres"
password = "123QQsuccess"
class DatabaseConnection:
def __init__(self):
try:
self.connection = psycopg2.connect(database=database, host=host, user=user, password=password)
self.connection.autocommit = True
self.cursor = self.connection.cursor()
except:
pprint('Cannot connect to database')
def insert_new_record(self):
new_record = ['one','two','three']
for item in new_record:
insert_command = "INSERT INTO products(products_amazon) VALUES ('" + item + "')"
pprint(insert_command)
self.cursor.execute(insert_command)
if __name__ == '__main__':
database_connection = DatabaseConnection()
database_connection.insert_new_record()
答案 0 :(得分:1)
$QUERY = "INSERT INTO emp_record(ename,ssn,dept,sallary,haddress) VALUES('$EName','$SSN','$Dept','$Salary','$HAddress')";
答案 1 :(得分:1)
如果出于某种原因你真的想一次插入所有语句,只需使用; 连接所有插入语句,并将其作为单个字符串发送到数据库。
像这样:
"INSERT INTO products(products_amazon) VALUES ('one');
INSERT INTO products(products_amazon) VALUES ('two');
INSERT INTO products(products_amazon) VALUES ('three');"