简体   繁体   中英

CSV file will not be imported into mysql database

So I am working on this assignment that gets rows of data from a CSV file and inserts it into a database. All my code is correct according to my professor's demo video, but the data is still not going into the table that I created in MySql. I also have a line print(cur.rowcount, "records inserted") that should print the number of rows my database has but returns -1. Any help would be appreciated, Thanks! (sorry if it hard to read)

import mysql.connector

import CSV

db = mysql.connector.connect(
    host = "localhost",
    user="root",
    passwd = "",
    database = "user_cards"
    )


cur = db.cursor()


f = open("UCI_Credit_Card.csv")

index = 0
for row in csv.reader(f):

    if index==0:
            index+1
    else:
            ID = row[0]
            LIMITBAL = row[1]
            SEX = row[2]
            EDUCATION = row[3]
            MARRIAGE = row[4]
            AGE = row[5]
            PAY_0 = row[6]
            PAY_2 = row[7]
            PAY_3 = row[8]
            PAY_4 = row[9]
            PAY_5 = row[10]
            PAY_6 = row[11]
            BILL_AMT1 = row[12]
            BILL_AMT2 = row[13]
            BILL_AMT3 = row[14]
            BILL_AMT4 = row[15]
            BILL_AMT5 = row[16]
            BILL_AMT6 = row[17]
            PAY_AMT1 = row[18]
            PAY_AMT2 = row[19]
            PAY_AMT3 = row[20]
            PAY_AMT4 = row[21]
            PAY_AMT5 = row[22]
            PAY_AMT6 = row[23]
            payment_next_month = row[24]

            sql = "INSERT INTO customers (ID, LIMITBAL, SEX, EDUCATION, MARRIAGE, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2, BILL_AMT3,BILL_AMT4, BILL_AMT5, BILL_AMT6, PAY_AMT1, PAY_AMT2, PAY_AMT3, PAY_AMT4, PAY_AMT5, PAY_AMT6, payment_next_month) VALUES (%s, %s, %s, %s, %s, %s, %s, %s,%s, %s,%s, %s, %s, %s, %s,%s, %s, %s, %s ,%s ,%s, %s, %s,%s, %s)"
            val = (ID, LimitBal, SEX, EDUCATION, Marriage, AGE, PAY_0, PAY_2, PAY_3, PAY_4, PAY_5, PAY_6, BILL_AMT1, BILL_AMT2,BILL_AMT3,BILL_AMT4,BILL_AMT5,BILL_AMT6,PAY_AMT1,PAY_AMT2,PAY_AMT3,PAY_AMT4,PAY_AMT5,PAY_AMT6,payment_next_month)

            cur.execute(sql, val)

            db.commit()

print(cur.rowcount, "records inserted")

db.close

A small mistake in index+1 .

I think you mean index += 1 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM