Python 处理MySQL

1 将CSV文件数据写入MySQL
Supplier Name Invoice Number Part Number Cost Purchase Date
Supplier X 001-1001 2341 500.001/20/14SupplierX00110012341 500.00 1 / 20 / 14 S u p p l i e r X 001 − 1001 2341 500.00 1/20/14
Supplier X 001-1001 5467 750.001/20/14SupplierX00110015467 750.00 1 / 20 / 14 S u p p l i e r X 001 − 1001 5467 750.00 1/20/14
Supplier Y 50-9501 7009 250.001/30/14SupplierY5095017009 250.00 1 / 30 / 14 S u p p l i e r Y 50 − 9501 7009 250.00 1/30/14
Supplier Y 50-9505 6650 125.002002/3/14SupplierY5095056650 125.00 2002 / 3 / 14 S u p p l i e r Y 50 − 9505 6650 125.00 2002/3/14
Supplier Z 920-4803 3321 615.002002/3/14SupplierZ92048043321 615.00 2002 / 3 / 14 S u p p l i e r Z 920 − 4804 3321 615.00 2002/10/14
Supplier Z 920-4805 3321 615.002/17/14SupplierZ92048063321 615.00 2 / 17 / 14 S u p p l i e r Z 920 − 4806 3321 615.00 2/24/14

import csv
import MySQLdb as mysql
import sys
from datetime import datetime,date
input_file='supplier_data.csv'
con=mysql.connect(host='localhost',port=3306,db='my_suppliers',user='root',passwd='123456')
c=con.cursor()
file_reader=csv.reader(open(input_file,'r',newline=''))
header=next(file_reader)
for row in file_reader:
    data=[]
    for column_index in range(len(header)):
        if column_index <4:
            data.append(str(row[column_index]).lstrip('$').replace(',','').strip())
        else:
            a_date=datetime.date(datetime.strptime(str(row[column_index]),'%m/%d/%y'))
            a_date=a_date.strftime('%Y-%m-%d')
            data.append(a_date)
    print(data)
    c.execute("""INSERT INTO Suppliers VALUES (%s,%s,%s,%s,%s);""",data)
con.commit()
print("")
c.execute("select * from suppliers")
rows=c.fetchall()
for row in rows:
    row_list_output=[]
    for column_index in range(len(row)):
        row_list_output.append(str(row[column_index]))
    print(row_list_output)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值