我正在尝试使用db
向sqlalchemy
表中插入一些虚拟值。但是我遇到'AttributeError: 'tuple' object has no attribute 'keys'
错误,
from sqlalchemy import Table, Column, Integer, String, Float, create_engine, MetaData
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
engine= create_engine('sqlite:///test.db')
Session = sessionmaker(bind=engine)
metadata = MetaData(bind=engine)
s = Session()
Base = declarative_base()
Base.metadata.create_all(engine)
Base.metadata.bind = engine
s.execute('DROP TABLE IF EXISTS person')
s.execute(
'CREATE TABLE person (id INTEGER NOT NULL, '
' name VARCHAR(255),'
' PRIMARY KEY (id))')
s.commit()
for i in range(10):
row = ('name-{}'.format(i),)
s.execute("INSERT INTO person (name) VALUES (?)",(row))
s.commit()
尝试运行以上代码时,我得到以下AttributeError
:
Traceback (most recent call last):
File "C:\Users\ashesh\DataWarehouse\Projects\Project-1\project1.py", line 30, in <module>
s.execute("INSERT INTO person (name) VALUES (?)",(row))
File "C:\Users\DELL\Anaconda3\lib\site-packages\sqlalchemy\orm\session.py", line 1176, in execute
bind, close_with_result=True).execute(clause, params or {})
File "C:\Users\DELL\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 948, in execute
return meth(self, multiparams, params)
File "C:\Users\DELL\Anaconda3\lib\site-packages\sqlalchemy\sql\elements.py", line 269, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "C:\Users\DELL\Anaconda3\lib\site-packages\sqlalchemy\engine\base.py", line 1028, in _execute_clauseelement
keys = list(distilled_params[0].keys())
AttributeError: 'tuple' object has no attribute 'keys'
答案 0 :(得分:1)
您可以改用以下语法:
for i in range(10):
row = 'name-{}'.format(i)
s.execute("INSERT INTO person (name) VALUES (:name)", {'name':row})