Home > Back-end >  how to add data in a mysql table
how to add data in a mysql table

Time:10-22

so i was creating a menu option where user enters some data and using a function all of that data is added to a MySQL table however the data table is not being updated properly I have checked there is nothing wrong with the table created so I think the problem lies in the code somewhere

import mysql.connector
def add_det(x1, x2, x3, x4):
                global icode, iname, price, quantity
                try:
                    conn=mysql.connector.connect(host='localhost', database='practicals', user='root', password='root1')
                    cursor=conn.cursor()
                    print("cursor objected created")
                    sql = """#INSERT INTO inventory(item_code, item_name, price, quantity) VALUES (%s,%s,%s,%s)"""
                    t=(x1, x2, x3, x4)
                    print(t)
                    cursor.execute(sql)
                    conn.commit()
                    print(cursor.rowcount, "Records inserted")
                except mysql.connector.Error as e:
                    print("Failed to get record from Mysql table: {}", format(error))
                finally:
                    if conn.is_connected():
                        print("closing...")
                        cursor.close()
                        conn.close()
                        print("Mysql connection is closed")
            add_det(icode, iname, price, quantity)

could anyone pls help me in finding the error?

CodePudding user response:

What happens when you remove the # in front of your SQL query?

Or try to change your code with:

sql = """#INSERT INTO inventory(item_code, item_name, price, quantity) 
    VALUES ({}, {}, {}, {})""".format(
    x1, x2, x3, x4
)
  • Related