2013-03-26 47 views
1

我一直在研究如何將包含7個元素(列)的〜500元組(行)的列表插入到數據庫中。我已閱讀了各種帖子在stackoverflow以及其他論壇。我發現了以下內容,它建議使用'executemany()'方法,但它對我來說不太清楚。我是否需要將我的對象從元組轉換爲字典?問題是我沒有一個名稱:值類型的數據結構。python sqlalchemy在元組數據結構中插入多行

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) 
+0

看起來你必須根據教程提供一個詞典列表'要使用DBAPI的executemany()方法發出多個插入,我們可以發送一個詞典列表,每個詞典包含一組不同的要插入的參數,因爲我們在這裏添加一些電子郵件地址:'。只需將元組轉換爲字典即可。 – CppLearner 2013-03-26 02:26:41

+0

謝謝CppLearner。所以,當我將元組轉換爲字典時,它與* key *字段有什麼關係?關鍵字段是否必須與表中的列名匹配?感謝你的幫助。謝謝。 – codingknob 2013-03-26 04:05:24

+0

是的!字典關鍵字的名稱應與數據庫中的屬性(或字段)名稱匹配!所以請使用您爲Column創建的任何內容。 Ť – CppLearner 2013-03-26 04:51:56

回答

1

嗯,我做了以下內容:

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. 

在任何情況下,這是我需要研究的另一個問題。這就是說,我正在回答和接受這個問題,因爲上面的字典應該可以工作。