#!/usr/bin/env python3
# _*_ coding:utf-8 _*_
import pymysql
from datetime import datetime
import logging
# 配置logging
logging.basicConfig(level=logging.WARNING,filename="./log.log", format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
# 利用pymysql连接数据库
conn = pymysql.connect(host="127.0.0.1", port=3306, user="root", password="123456", db="test", charset="utf8")
cur = conn.cursor()
# 设置一个空列表保存数据
line_list = []
# 从csv文件中读取整理数据
with open("new_bb.txt", "r")as f: # 文件中的数据格式是 2019/05/16 17:36:02,113,207.46.13.30
for line in f: # 以行为单位读取csv文件的内容
line = line.split(",")
a = datetime.strptime(line[0], "%Y/%m/%d %H:%M:%S") # 把字符格式的时间转换为mysql数据库datatime类型认识的时间类型
b = line[1]
c = line[-1].strip()
line = (int(b), c, a)
line_list.append(line) # 出家数据到line_list列表
print(len(line_list))
for row in line_list:
sql ="insert into history_blacklist_ip(access_num,access_ip,create_time) value(%s,%s,%s)"
params = row
line = sql % params
try:
cur.execute(sql, params)
conn.commit()
except Exception as e:
conn.rollback()
print(line)
logger.warning(e)
logger.warning(line)
conn.close()
网友评论