读取后插入MySQl数据库?

2024-04-29 08:57:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的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数据库中,但是不知怎么的,在迭代了我得到的列表之后,我被困在如何插入MySQL数据库中了。在

查询如下:

^{pr2}$

下面是代码

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

from collections import defaultdict

lst = defaultdict(list)
d_lst = defaultdict(list)

# ======================== 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):

   domain_list = []
   domain_date_list = []
   sorted_domain_list_bydate = defaultdict(list)

   with open(filepath, 'rb') as csvfile:
       reader = csv.reader(csvfile)

       for row in reader:
          # insert the 1st & 2nd column of the CSV file into a set called input_list
           email = row[0].strip().lower()
           date  = row[1].strip()

           domain_date_list.append([date, email[ email.find("@") : ]])
           domain_list.append(email[ email.find("@") : ])

   for k, v in domain_date_list: 
         sorted_domain_list_bydate[k].append(v)


   # remove duplicates from domain list
   domain_list = list(set(domain_list))

   return sorted_domain_list_bydate, domain_list
# ===========================================================
def update_DB(lst):

    # open a database connection
    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() 

    a = []
    for k, v in lst.items():
        # now what should I do here?
        # this is what I am confuse

    db.commit()
    db.close()
# ==========================================================

# ======================= main program =======================================
path = get_file_path('emails.csv') 
[lst, d_lst] = read_CSV(path) # read the input file
update_DB(lst) # insert data into domains table

我在update_DB方法中感到困惑。在


Tags: csvthepathimportdbdateemaildomain
1条回答
网友
1楼 · 发布于 2024-04-29 08:57:16

我不知道为什么你有这么复杂的程序来完成一个简单的任务。让我们从顶部开始:

  1. 首先需要按域、日期和计数正确组织数据。

    import csv
    from collections import defuaultdict, Counter
    
    domain_counts = defaultdict(Counter)
    
    with open('somefile.csv') as f:
        reader = csv.reader(f)
        for row in reader:
            domain_counts[row[0].split('@')[1].strip()][row[1]] += 1
    
  2. 接下来,您需要在数据库中正确插入每个

    ^{2美元

由于没有正确插入日期,请尝试使用此更新的查询:

q = """INSERT INTO 
          domains(domain_name, cnt, date_of_entry)
          VALUES(%s, %s, STR_TO_DATE(%s, '%d-%m-%Y'))"""
网友
2楼 · 发布于 2024-04-29 08:57:16

这里的read_csv函数返回sorteddomainlistbydate,以及update_db函数使用的domain_list(这是一个列表),您可以在这里执行插入操作。

您的列表只包含域名,而每对密钥VAL应包含域名和计数 像

在谷歌,2

在live.com网站,1

for k, v in lst.items():
     cur.execute("INSERT INTO domains(domain_name, cnt, date_of_entry) VALUES ('" + str(k) + "','" + str(v) + "','" + str(time.strftime("%d/%m/%Y"))+"')")

相关问题 更多 >