Search code examples
pythonmysqlmysql-error-1062mysql-error-1205

mysql insert error both in python and mysql command line


I want to insert some items to mysql db.

When I did it in my python script, I got:

Error 1062: Duplicate entry '222' for key 'product_code'. product_code is an unique field.

When I did it in mysql command line, I got:

Error 1205(HY000):Lock wait timeout exceed; try restarting transaction.

Mysql is installed on win32; the table's engine is innodb.

code:

conn = mdb.connect(user = 'root', passwd = '[REMOVED]', db = 'vancl')
cur = conn.cursor()

sql2 = "insert into vancl.vancl_query1(product_code) values('100000')"
print sql2
cur.execute(sql2)

cur.close()

Solution

  • Now, I recreate a table the same as prev one. In script, no error was reported, but in actually no data is inserted. In command line, insert sql works perfect.

    Your data will not be saved if you use a transaction engine like InnoDB because MySqlDb default to auto-commit off. To actually save data to database, you have to call commit

    conn = mdb.connect(user = 'root', passwd = '[REMOVED]', db = 'vancl')
    cur = conn.cursor()
    
    sql2 = "insert into vancl.vancl_query1(product_code) values('100000')"
    print sql2
    
    cur.execute(sql2)
    
    //Commit the data
    conn.commit() 
    
    cur.close()