gpt4 book ai didi

python - 类型错误 : not enough arguments for format string while inserting into mysql database

转载 作者:行者123 更新时间:2023-11-29 06:21:15 25 4
gpt4 key购买 nike

我有一个这样的 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 表中。

下面是给我错误的代码 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 中。

最佳答案

您的 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'))"""

关于python - 类型错误 : not enough arguments for format string while inserting into mysql database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33195964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com