2015-10-18 55 views
1

我有一個CSV文件是這樣的:類型錯誤:沒有足夠的論據格式的字符串,而插入到mysql數據庫

[email protected], 01-05-2014 
[email protected], 01-05-2014 
[email protected], 01-05-2014 
[email protected], 01-05-2014 

我讀上面的CSV文件,並提取域名,也電子郵件地址由計數域名和日期。所有這些我需要插入MySQL表中的所謂的域。

下面是代碼,其中給我的錯誤爲TypeError: not enough arguments for format string,它發生在我嘗試插入domains表中時發生。

#!/usr/bin/python 
import fileinput 
import csv 
import os 
import sys 
import time 
import MySQLdb 

from collections import defaultdict, Counter 

domain_counts = defaultdict(Counter) 

# ======================== Defined Functions ====================== 
def get_file_path(filename): 
    currentdirpath = os.getcwd() 
    # get current working directory path 
    filepath = os.path.join(currentdirpath, filename) 
    return filepath 
# =========================================================== 
def read_CSV(filepath): 

    with open('emails.csv') as f: 
     reader = csv.reader(f) 
     for row in reader: 
      domain_counts[row[0].split('@')[1].strip()][row[1]] += 1 

    db = MySQLdb.connect(host="localhost", # your host, usually localhost 
         user="root", # your username 
         passwd="abcdef1234", # your password 
         db="test") # name of the data base 
    cur = db.cursor() 

    q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, '%d-%m-%Y'))""" 

    for domain, data in domain_counts.iteritems(): 
     for email_date, email_count in data.iteritems(): 
      cur.execute(q, (domain, email_count, email_date)) 

    db.commit() 

# ======================= main program ======================================= 
path = get_file_path('emails.csv') 
read_CSV(path) # read the input file 

我在做什麼?

截至目前我的數據類型爲date_of_entry列是date在MySQL中。

回答

2

你還需要「%D-%間%Y」在你的SQL語句確切這種方式。但python(或執行命令)首先嚐試將其用於字符串格式並引發此錯誤。

我認爲你必須逃避它,你應該嘗試以下操作:

q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, '%%d-%%m-%%Y'))""" 
+0

非常感謝。它確實工作.. – john

+0

我有另一個問題[這裏](http://stackoverflow.com/questions/33196264/find-top-x-by-count-from-mysql-in-python)。看看你能幫忙嗎? – john

0

試試這個:

q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, 'd-m-Y'))""" 

因此我們必須從STR_TO_DATE(%s, '%d-%m-%Y'))改爲STR_TO_DATE(%s, 'd-m-Y'))

+0

有了這個,我得到一個錯誤的'_mysql_exceptions.OperationalError:(1048,「列date_of_entry「不能爲空」)' – john

0

據檢測%S作爲格式字符串和失敗上。你需要用引號包圍它,我想

INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE('%s', '%d-%m-%Y')) 
+0

有了這個,我得到這個錯誤'TypeError:沒有足夠的參數格式字符串' – john

相關問題