【问题标题】:Using phpmyadmin, have a mysql database loaded and am trying to alter the DB using python使用 phpmyadmin,加载 mysql 数据库并尝试使用 python 更改数据库
【发布时间】:2020-05-23 21:32:23
【问题描述】:

我正在尝试:

  1. 更新数据,使marriage=2(单身)和marriage=3(其他)合并为2(单身)。 和:
  2. 删除所有具有负 BILL_AMT 值的数据记录(在任何 BILL_AMT1 到 BILL_AMT6 中)

问题是我运行代码,得到所有清晰的消息,检查数据库,似乎没有任何改变...#1 可能工作,但我不知道如何使用所有行运行它当我回顾数据库时,#2 似乎没有任何改变:

import csv

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="",
  database="hw6"
)

mycursor = mydb.cursor()


f = open("UCI_Credit_Card.csv")
for row in csv.reader(f):
    a= row[0]
    b= row[1]
    c= row[2]
    d= row[3]
    e= row[4]
    f= row[5]
    g= row[6]
    h= row[7]
    i= row[8]
    j= row[9]
    k= row[10]
    l= row[11]
    m= row[12]
    n= row[13]
    o= row[14]
    p= row[15]
    q= row[16]
    r= row[17]
    s= row[18]
    t= row[19]
    u= row[20]
    v= row[21]
    w= row[22]
    x= row[23]
    y= row[24]
    sql = "INSERT INTO customers (ID, LIMIT_BAL, 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, default_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 = (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y)
    mycursor.execute(sql, val)

mydb.commit()

print(mycursor.rowcount, "record inserted.")


mycursor = mydb.cursor(buffered=True)
print("Before updating a record ")
sql_select_query = """select * from customers"""
mycursor.execute(sql_select_query)
record = mycursor.fetchone()
print(record)

# Update single record now
sql_update_query = """UPDATE CUSTOMERS SET SEX = 2 where SEX = 3"""
mycursor.execute(sql_update_query)
mydb.commit()
print("Record Updated successfully ")

print("After updating record ")
mycursor.execute(sql_select_query)
record = mycursor.fetchone()
print(record)


# Delete record now
mycursor = mydb.cursor(buffered=True)
sql_update_query = "DELETE FROM customers WHERE (BILL_AMT1<0)AND(BILL_AMT2<0)AND(BILL_AMT3<0)AND(BILL_AMT4<0)AND(BILL_AMT5<0)AND(BILL_AMT6<0) """
sql_delete_query = """select * from customers"""
mycursor.execute(sql_update_query)
mydb.commit()
print("Record Delete successfully ")```

【问题讨论】:

    标签: python mysql sql sql-delete


    【解决方案1】:

    UPDATE 语句看起来不错。

    但是说到第二个要求:

    删除所有带有负 BILL_AMT 值的数据记录(在任何 BILL_AMT1 到 BILL_AMT6 中)

    大概,您在delete 查询中需要ored 条件而不是and

    DELETE FROM customers 
    WHERE  
        BILL_AMT1 < 0
        OR BILL_AMT2 < 0
        OR BILL_AMT3 < 0
        OR BILL_AMT4 < 0
        OR BILL_AMT5 < 0
        OR BILL_AMT6 < 0
    

    【讨论】:

    • 就是这样!记录被删除!对于更新语句,我怎样才能让它遍历数据库中的每一行?
    • @Joseph:您的 update 语句会更改 `sex = 3` 的每条记录 - 就您想要的而言。
    猜你喜欢
    • 2010-11-14
    • 2011-12-20
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 2016-10-15
    • 2014-05-27
    • 1970-01-01
    • 2021-05-19
    相关资源
    最近更新 更多