【问题标题】:TypeError: not enough arguments for format string while inserting into mysql databaseTypeError:插入mysql数据库时格式字符串的参数不足
【发布时间】:2016-01-16 17:03:44
【问题描述】:

我有一个这样的 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 文件并提取域名以及按域名和日期计算的电子邮件地址计数。我需要将所有这些东西插入到名为 domain 的 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

我做错了什么?

到目前为止,我在 MySQL 中 date_of_entry 列的数据类型是 date

【问题讨论】:

    标签: python mysql csv


    【解决方案1】:

    您需要以这种方式在您的 sql 语句中添加“%d-%m-%Y”。但是python(或执行命令)首先尝试将其用于字符串格式化并抛出此错误。

    我认为你必须逃避它,你应该尝试以下操作:

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

    【讨论】:

    • 我还有一个问题here。看看你能不能帮忙?
    【解决方案2】:

    试试这个:

    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'))

    【讨论】:

    • 有了这个我得到一个错误_mysql_exceptions.OperationalError: (1048, "Column 'date_of_entry' cannot be null")
    【解决方案3】:

    它正在将 %s 检测为格式字符串,但未能成功。我猜你需要用引号括起来

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

    【讨论】:

    • 有了这个,我收到了这个错误TypeError: not enough arguments for format string
    猜你喜欢
    • 2019-01-17
    • 2017-12-18
    • 2018-06-07
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2012-06-24
    • 2020-10-17
    • 2012-06-11
    相关资源
    最近更新 更多