Devdit
 

AttributeError: 'MySQLCursor' object has no attribute 'commit' Python คือ วิธีแก้ไข

2.4K

รันโปรแกรมภาษา Python เพิ่มข้อมูลลงฐานข้อมูล MySQL แต่ขึ้น Error ว่า AttributeError: 'MySQLCursor' object has no attribute 'commit' ต้องแก้ไขโค้ดส่วนไหน

if( title != '' and price > 0 ):
    conn = connect()
    cur = conn.cursor()
    cur.execute( " INSERT INTO product ( id, title, price ) VALUES ( NULL, %s, %s ) ", ( title, price, ) )
    cur.commit()
    print(cur.rowcount, "record(s) insert\n") 

 

วิธีแก้ไข

ปัญหานี้เกิดจากคำสั่งตรง cur.commit() คำสั่ง commit ต้องใช้กับตัวแปรที่เก็บค่าการเชื่อมต่อฐานข้อมูล ซึ่งต้องแก้ไขเป็น conn.commit()

if( title != '' and price > 0 ):
    conn = connect()
    cur = conn.cursor()
    cur.execute( " INSERT INTO product ( id, title, price ) VALUES ( NULL, %s, %s ) ", ( title, price, ) )
    conn.commit()
    print(cur.rowcount, "record(s) insert\n") 
แก้ไข 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ