1

I am trying to insert values into a mysql table using python,I have some values but i donot consider whether duplicate keys/non duplicate but i want every values to be inserted.

For my mysql coding what changes should i make to insert duplicates?

   for name,hobby in p: 
       print name,hobby

   cursor.execute(
   '''INSERT INTO Details (Names, Hobby)
      VALUES (%s, %s)''',
     (name,hobby))

I get the following error!

   IntegrityError: (1062, "Duplicate entry 'Leelal' for key 'PRIMARY'")

Please help me in getting the duplicate values into the table!

Table schema:

Id | Names | Hobby

Is there a way to auto increment Id as long as the Names and Hobby present in list?

1
  • 1
    Please show us the table schema you have, and the keys/indexes it has. There's no way you can both add duplicates and preserve your primary key. Commented Jul 29, 2014 at 16:24

2 Answers 2

2

If an attribute (column) in the table is a primary key (or unique), it can never accept duplicates. As long as your primary key (may be ID) do not have duplicates, you can pretty much insert duplicates For example,

ID   |   Name   |   Hobby  |
1        John       Play
2        John       Play
3        Steve      Running
4        Steve      Running

(Make sure that you set your primary key to auto increment. Here is the tutorial: http://www.w3schools.com/sql/sql_autoincrement.asp).

CREATE TABLE Hobbies
(
ID int NOT NULL AUTO_INCREMENT,
Name varchar(255) NOT NULL,
Hobby varchar(255),
PRIMARY KEY (ID)
)
Sign up to request clarification or add additional context in comments.

6 Comments

but i need to increment id as the Names and Hobby present,so does it increment automatically/should i make changes?
@user3886307 If your ID is primary key, then yes, your ID would be automatically be incremented
@GravityM - Is that true in MySQL? If they only set it as the primary key does it auto increment? I would suspect that they need to do the AUTO_INCREMENT. Based on this post, it does not appear you can make it a function to increment it for you.
@user3886307 Yes, ID is of type integer and you should set the Auto Increment.
how to set the Auto Increment?
|
0

I would assume that the problem is that your Details table has a primary key setup. In order to insert duplicates, you would need to remove the primary key, or change it to be unique enough that it's not considered a duplicate.

Look at your Table create script, I would assume you have something like this

CREATE TABLE Persons
(
ID int NOT NULL,
Name varchar(255) NOT NULL,
Hobby varchar(255),
PRIMARY KEY (Name)
)

Remove the PRIMARY KEY.

If you want to have Id as the primary, create your table something like this

CREATE TABLE MyTable
(
ID INTEGER AUTO_INCREMENT PRIMARY KEY
Name varchar(255) NOT NULL,
Hobby varchar(255),
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.