UnicodeEncodeError:'ascii'编解码器在将csv导出到mysql时无法编码

时间:2014-03-19 17:15:29

标签: python python-2.7

我正在尝试将csv文件导出到mysql,每次尝试打印时都会收到此错误。 任何帮助将不胜感激。我现在不在哪里我错了..

  reader = csv.reader(open(csvfile, 'r'))

    for row in reader:
        print row
        try:
            (location_id, vrm, valid_datetime) = row
        except:
            print "Error with row: " % row
            #sys.exit(3)


        # Hack for Roseburys
        if (location_id == 262):
            location_id = "198"
        if (location_id == "262"):
            location_id = "198"


        tmp = valid_datetime.split(" ")
        valid_date = tmp[0]

        # Tidy up the VRM
        vrm = vrm.replace(' ', '')
        vrm = vrm.upper()

        tmp = valid_date.split('/')
        iso_date = "%s-%s-%s" % (tmp[2], tmp[1], tmp[0])
        entryDatetime = "%s 00:00:00" % iso_date
        expiryDatetime = "%s 23:59:59" % iso_date
        sql_local = """INSERT INTO customer_1.pay_and_display
            (plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price)
            VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (vrm, location_id, entryDatetime, expiryDatetime, "WL", 0)
        print sql_local
        cursor.execute(sql_local)

1 个答案:

答案 0 :(得分:0)

reader = csv.reader(open(csvfile,'r'))

for row in reader:
    print row
    try:
        (location_id, vrm, valid_datetime) = row
    except:
        print "Error with row: " % row
        #sys.exit(3)


    # Hack for Roseburys
    if (location_id == 262):
        location_id = "198"
    if (location_id == "262"):
        location_id = "198"


    tmp = valid_datetime.split(" ")
    valid_date = tmp[0]

    # Tidy up the VRM
    vrm = vrm.replace(' ', '')
    vrm = vrm.upper()

    tmp = valid_date.split('/')
    iso_date = "%s-%s-%s" % (tmp[2], tmp[1], tmp[0])
    entryDatetime = "%s 00:00:00" % iso_date
    expiryDatetime = "%s 23:59:59" % iso_date
    sql_local = """INSERT INTO customer_1.pay_and_display
        (plate, machine_id, ticket_datetime, expiry_datetime, ticket_name, ticket_price)
        VALUES ("%s", "%s", "%s", "%s", "%s", "%s") """ % (vrm, location_id, entryDatetime, expiryDatetime, "WL", 0)
    print sql_local
    cursor.execute(sql_local)