Minglong
Minglong

Reputation: 129

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()

Upvotes: 1

Views: 367

Answers (2)

Kien Truong
Kien Truong

Reputation: 11381

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()

Upvotes: 0

user1452106
user1452106

Reputation:

That means that the product_code column has a unique index constraint placed on it. A unique index constraint tells MySQL that a field cannot have duplicate values, i.e. that each field must be unique. What you've got there is a 'duplicate entry' error from trying to insert the value 222 into product_code when that value already exists somewhere in the column.

Upvotes: 0

Related Questions