所以我正在做这个作业,从 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
qq_遁去的一_1
相关分类