Python 2.6.4+ScrapyツールキットでWebスクレイパーを作成します。データ分析を行う必要がありますが、私の最初のPython学習プロジェクトでもあります。私のpipeline.pyでSQLINSERTステートメントを作成するのに問題があります。実際のクエリには、挿入する属性が約30個あります。
まず、このUPDATEまたはINSERTアルゴリズムを作成するためのより良い方法はありますか?改善の余地があります。
次に、2つの異なる構文のバリエーションと、それらが生成するさまざまなエラーを示します。例に基づいて多くのバリエーションを試しましたが、複数行にまたがる「INSERTSET」を使用した例を見つけることができません。適切な構文は何ですか?
DBは空なので、今のところ常に「INSERT」ブロックに分岐しています。
def _conditional_insert(self, tx, item):
# create record if doesn't exist.
tx.execute("SELECT username FROM profiles_flat WHERE username = %s", (item['username'][0], ))
result = tx.fetchone()
if result:
# do row UPDATE
tx.execute( \
"""UPDATE profiles_flat SET
username=`%s`,
headline=`%s`,
age=`%s`
WHERE username=`%s`""", ( \
item['username'],
item['headline'],
item['age'],)
item['username'],)
)
else:
# do row INSERT
tx.execute( \
"""INSERT INTO profiles_flat SET
username=`%s`,
headline=`%s`,
age=`%s` """, ( \
item['username'],
item['headline'],
item['age'], ) # line 222
)
エラー:
[Failure instance: Traceback: <class '_mysql_exceptions.OperationalError'>: (1054, "Unknown column ''missLovely92 '' in 'field list'")
/usr/lib/python2.6/threading.py:497:__bootstrap
/usr/lib/python2.6/threading.py:525:__bootstrap_inner
/usr/lib/python2.6/threading.py:477:run
--- <exception caught here> ---
/usr/lib/python2.6/vendor-packages/twisted/python/threadpool.py:210:_worker
/usr/lib/python2.6/vendor-packages/twisted/python/context.py:59:callWithContext
/usr/lib/python2.6/vendor-packages/twisted/python/context.py:37:callWithContext
/usr/lib/python2.6/vendor-packages/twisted/enterprise/adbapi.py:429:_runInteraction
/export/home/raven/scrapy/project/project/pipelines.py:222:_conditional_insert
/usr/lib/python2.6/vendor-packages/MySQLdb/cursors.py:166:execute
/usr/lib/python2.6/vendor-packages/MySQLdb/connections.py:35:defaulterrorhandler
]
代替構文:
query = """INSERT INTO profiles_flat SET
username=`%s`,
headline=`%s`,
age=`%s` """ % \
item['username'], # line 196
item['headline'],
item['age']
tx.execute(query)
エラー:
[Failure instance: Traceback: <type 'exceptions.TypeError'>: not enough arguments for format string
/usr/lib/python2.6/threading.py:497:__bootstrap
/usr/lib/python2.6/threading.py:525:__bootstrap_inner
/usr/lib/python2.6/threading.py:477:run
--- <exception caught here> ---
/usr/lib/python2.6/vendor-packages/twisted/python/threadpool.py:210:_worker
/usr/lib/python2.6/vendor-packages/twisted/python/context.py:59:callWithContext
/usr/lib/python2.6/vendor-packages/twisted/python/context.py:37:callWithContext
/usr/lib/python2.6/vendor-packages/twisted/enterprise/adbapi.py:429:_runInteraction
/export/home/raven/scrapy/project/project/pipelines.py:196:_conditional_insert
]