我正在学习 SQL Alchemy。我有一个 CSV 文件中的列名称列表。我想为每一行创建插入语句(或为所有行创建一个插入语句)。到目前为止我已经
with open('tablename.csv', 'r') as f:
reader = csv.reader(f)
columns = next(reader)
for data in reader:
query = insert(table(table_name), columns, data)
print(str(query))
这只是打印
INSERT INTO tablename () VALUES ()
对于 CSV 文件中的每一行。
如何正确提供列名称和值?
最佳答案
编译后的 INSERT 语句为空的原因有两个: light weight table construct你用过没有columns定义,并且
insert()
的前 3 个参数是表,values和内联——不是表、列和值。遇到麻烦时,阅读相关文档是一个好的开始。
SQLAlchemy 插入构造可以仅由 passing it to execute, accompanied with the desired values 使用,或作为单个 INSERT ... VALUES ...
语句。无论哪种方式,如果不传递完整的表元组,您都必须传递列、值对的字典:
tbl = table(table_name, *(column(c) for c in columns))
values = [dict(zip(columns, data)) for data in reader]
# A single INSERT statement with multiple values
stmt = insert(tbl).values(values)
engine.execute(stmt)
# More traditional executemany
engine.execute(insert(tbl), values)
关于python - 创建插入对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46410413/