gpt4 book ai didi

python sqlalchemy 在元组数据结构中插入多行

转载 作者:太空宇宙 更新时间:2023-11-03 19:02:41 25 4
gpt4 key购买 nike

我一直在研究如何将包含 7 个元素(列)的约 500 个元组(行)的列表插入到数据库中。我阅读了 stackoverflow 以及其他论坛上的各种帖子。我发现了以下内容,它建议使用“executemany()”方法,但我不太清楚如何使用。我是否需要将对象从元组转换为字典?问题是我没有 name:value 类型的数据结构。

How to use SQLAlchemy to dump an SQL file from query expressions to bulk-insert into a DBMS?

Here is an example:

engine = create_engine('sqlite:///:memory:', echo=True)
metadata = MetaData()
hockey= Table('hockey', metadata,
Column('team', String(16), primary_key=True),
Column('jersey_colour', String(16)),
Column('stadium', String(32)),
Column('goals', Integer),
Column('date', Date, primary_key=True),
Column('assists', Integer))

>>>data[0]
[(u'Maple Leafs', u'Blue', u'Air Canada Center', 151, '2013-03-25', 301)]

编辑:

我尝试了描述的解决方案( Sqlalchemy core, insert multiple rows from a tuple instead of dict ),如下所示:

markers = ','.join('?' * len(data[0]))
ins = 'INSERT INTO {tablename} VALUES ({markers})'
ins = ins.format(tablename=hockey.name, markers=markers)

>>str(ins)
'INSERT INTO hockey VALUES (?,?,?,?,?,?)'

conn = engine.connect()
result = conn.execute(ins, data)

In [59]: result = conn.execute(ins, data)
2013-03-26 07:29:28,371 INFO sqlalchemy.engine.base.Engine INSERT INTO hockey VALUES (?,?,?,?,?,?)
2013-03-26 07:29:28,371 INFO sqlalchemy.engine.base.Engine (u'Maple Leafs', u'Blue', u'Air Canada Center', 151, '2013-03-25', 301)
2013-03-26 07:29:28,371 INFO sqlalchemy.engine.base.Engine ROLLBACK
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
<ipython-input-59-dafe2aef2c66> in <module>()
----> 1 result = conn.execute(ins, data)

/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.pyc in execute(self, object, *multiparams, **params)
662 object,
663 multiparams,
--> 664 params)
665 else:
666 raise exc.InvalidRequestError(

/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.pyc in _execute_text(self, statement, multiparams, params)
806 statement,
807 parameters,
--> 808 statement, parameters
809 )
810 if self._has_events:

/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
876 parameters,
877 cursor,
--> 878 context)
879 raise
880

/usr/lib/python2.7/site-packages/sqlalchemy/engine/base.pyc in _execute_context(self, dialect, constructor, statement, parameters, *args)
869 statement,
870 parameters,
--> 871 context)
872 except Exception, e:
873 self._handle_dbapi_exception(

/usr/lib/python2.7/site-packages/sqlalchemy/engine/default.pyc in do_execute(self, cursor, statement, parameters, context)
318
319 def do_execute(self, cursor, statement, parameters, context=None):
--> 320 cursor.execute(statement, parameters)
321
322 def do_execute_no_params(self, cursor, statement, context=None):

OperationalError: (OperationalError) near "hockey": syntax error 'INSERT INTO hockey VALUES (?,?,?,?,?,?)' (u'Maple Leafs', u'Blue', u'Air Canada Center', 151, '2013-03-25', 301)

出现错误:

  OperationalError: (OperationalError) near "hockey": syntax error 'INSERT INTO hockey VALUES (?,?,?,?,?,?)' (u'Maple Leafs', u'Blue', u'Air Canada Center', 151, '2013-03-25', 301)

最佳答案

我做了以下事情:

column_names = tuple(c.name for c in hockey.c)

>>>column_names
('team', 'jersey_colour', 'stadium', 'goals', 'date', 'assists')

final = [dict(zip(column_names,x)) for x in data]

上面为每一行或每行创建了一个字典列表。这应该有效,但是当我运行时出现以下错误:

>>>conn.execute(ins, final)

SQLite Date type only accepts Python date objects as input.

无论如何,这是我需要研究的另一个问题。也就是说,我回答并接受这个问题是因为上面的字典应该有效。

关于python sqlalchemy 在元组数据结构中插入多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15628131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com