Python TypeError:插入mysql数据库时,格式字符串的参数不足
我有一个如下的csv文件:Python TypeError:插入mysql数据库时,格式字符串的参数不足,python,mysql,csv,Python,Mysql,Csv,我有一个如下的csv文件: nohaelprince@uwaterloo.ca, 01-05-2014 nohaelprince@uwaterloo.ca, 01-05-2014 nohaelprince@uwaterloo.ca, 01-05-2014 nohaelprince@gmail.com, 01-05-2014 我正在阅读上面的csv文件,并提取域名以及按域名和日期列出的电子邮件地址数。我需要将所有这些东西插入MySQL表中,称为domains 下面是代码,其中的错误为TypeEr
nohaelprince@uwaterloo.ca, 01-05-2014
nohaelprince@uwaterloo.ca, 01-05-2014
nohaelprince@uwaterloo.ca, 01-05-2014
nohaelprince@gmail.com, 01-05-2014
我正在阅读上面的csv文件,并提取域名以及按域名和日期列出的电子邮件地址数。我需要将所有这些东西插入MySQL表中,称为domains
下面是代码,其中的错误为TypeError:format string的参数不足,当我尝试插入域
表时,就会发生这种情况
#!/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
我做错了什么
到目前为止,我在MySQL中输入的date\u列的数据类型是date
。试试这个:
q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, 'd-m-Y'))"""
因此,我们已从STR\u改为\u日期(%s,%d-%m-%Y'))
改为STR\u改为\u日期(%s,'d-m-Y'))
它将%s检测为格式字符串,但失败了。我想你需要用引号括起来
INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE('%s', '%d-%m-%Y'))
sql语句中需要“%d-%m-%Y”的格式与此完全相同。但是python(或execute命令)首先尝试将其用于字符串格式化,并抛出此错误
我认为你必须摆脱它,你应该尝试以下几点:
q = """INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES(%s, %s, STR_TO_DATE(%s, '%%d-%%m-%%Y'))"""
有了这个,我得到了一个错误作为\u mysql\u exceptions.OperationalError:(1048,“列'date\u of\u entry'不能为null”)
有了这个错误,我得到了这个错误TypeError:格式字符串的参数不够
我还有一个问题。看看你能不能帮忙?