【问题标题】:CSV file will not be imported into mysql databaseCSV 文件不会导入 mysql 数据库
【发布时间】:2020-09-12 18:11:13
【问题描述】:

所以我正在做这个从 CSV 文件中获取数据行并将其插入数据库的任务。根据我教授的演示视频,我所有的代码都是正确的,但是数据仍然没有进入我在 MySql 中创建的表中。我还有一行 print(cur.rowcount, "records inserted") 应该打印我的数据库有但返回-1的行数。任何帮助将不胜感激,谢谢! (如果阅读困难,请见谅)

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

【问题讨论】:

标签: python mysql database csv


【解决方案1】:

index+1 中的一个小错误。

我想你的意思是index += 1

【讨论】:

    猜你喜欢
    • 2017-11-15
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    • 2019-02-21
    • 2016-11-17
    • 1970-01-01
    • 2021-12-30
    • 2017-01-21
    相关资源
    最近更新 更多