5

これは私の最初の投稿です!私プログラミングを始めたばかりですので、ご容赦ください!

後でデータに関するさまざまなレポートを実行するために、一連の.csvファイルをデータベースにロードしようとしています。私は、フィールド名とデータ型をテーブルにロードされるものと一致させるmysqlでいくつかのテーブルを作成することから始めました。(テーブルのフィールドとして使用する日付を解析するために)ファイル名を操作し、Pythonでデータをクリーンアップしています。

したがって、現在の私の問題(笑...)は、mysqlに対して「InsertInto」クエリを実行しようとすると、このエラーメッセージが表示されることです。

Traceback (most recent call last):  
File "C:\Program Files\Python\load_domains2.py", line 80, in <module>  
cur.execute(sql)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\cursors.py", line 166, in execute
self.errorhandler(self, exc, value)
File "C:\Program Files\Python\lib\site-packages\MySQLdb\connections.py", line 35, in defaulterrorhandler
raise errorclass, errorvalue
OperationalError: (1054, "Unknown column 'a1200e.com' in 'field list'")

「a1200e.com」は、その列に挿入している特定のドメイン名を指します。私の質問は次のとおりです。

sql="""INSERT INTO temporary_load
    (domain_name, session_count, search_count, click_count,
    revenue, revenue_per_min, cost_per_click, traffic_date)
    VALUES (%s, %d, %d, %d, %d, %d, %d, %s)""" %(cell[0],
                                                int(cell[1]),
                                                int(cell[2].replace (",","")),
                                                int(cell[3].replace(",","")),
                                                float(cell[4].replace("$","")),
                                                float(cell[5].replace("$","")),
                                                float(cell[6].replace("$","")),
                                                parsed_date)

    cur.execute(sql)

私はまったく新しいので、コードはまったく効率的ではないと確信していますが、すべてをレイアウトしたかったので、わかりやすくなっています。私が理解していないのは、テーブルに正しく定義されたデータ型(クエリのデータ型に対応)があることを確認したことです。足りないものはありますか?私はしばらくの間これを解決しようとしてきましたが、何が間違っているのかわかりません:/

本当にありがとう!!!ヴァル

4

2 に答える 2

2

Thomasは、いつものように完全に正しいです。MySQLdb に引用の問題を処理させてください。

その推奨事項に加えて:

  1. csv モジュールはあなたの友達です。
  2. PEP 249で詳述されているように、MySQLdb は「format」パラメータ スタイルを使用します。
    それはあなたにとって何を意味しますか?type
    に関係なく、 すべてのパラメータは文字列として MySQLdb に渡す必要があります (このように)。MySQLdb は、値が SQL リテラルに適切に変換されることを確認します。 ところで、MySQLdb には優れたドキュメントがいくつかあります。%s
  3. ソース データの詳細を自由に含めてください。これにより、問題の診断が容易になる場合があります。

.csv ファイルから MySQL データベースに値を挿入する 1 つの方法を次に示します。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv
import MySQLdb
import os

def main():
    db = MySQLdb.connect(db="mydb",passwd="mypasswd",) # connection string

    filename = 'data.csv'
    f = open(filename, "rb") # open your csv file
    reader = csv.reader(f)
    # assuming the first line of your csv file has column names
    col_names = reader.next() # first line of .csv file
    reader = csv.DictReader(f, col_names) # apply column names to row values

    to_db = [] # this list holds values you will insert to db
    for row in reader: # loop over remaining lines in .csv file
        to_db.append((row['col1'],row['col2']))
    # or if you prefer one-liners
    #to_db = [(row['col1'],row['col2']) for row in reader]
    f.close() # we're done with the file now

    cursor = db.cursor()
    cursor.executemany('''INSERT INTO mytable (col1,col2) 
                    VALUES (%s, %s)''', to_db) # note the two arguments
    cursor.close()
    db.close()

if __name__ == "__main__":
    main()
于 2010-02-10T04:55:48.727 に答える
1

SQL クエリにデータを直接含めるのではなく、DB-API 引用符を使用する必要があります。

sql = """INSERT INTO temporary_load
    (domain_name, session_count, search_count, click_count,
    revenue, revenue_per_min, cost_per_click, traffic_date)
    VALUES (%s, %d, %d, %d, %d, %d, %d, %s)"""
args = (cell[0],
        int(cell[1]),
        int(cell[2].replace (",","")),
        int(cell[3].replace(",","")),
        float(cell[4].replace("$","")),
        float(cell[5].replace("$","")),
        float(cell[6].replace("$","")),
        parsed_date)
cur.execute(sql, args)

これにより、DB-API モジュールは値を適切に引用し、手作業で (通常は誤って) 発生する可能性のある多くの問題を解決します。

于 2010-02-09T02:05:31.433 に答える