2

I have a simple table in MySQL which looks like this:

> ID | username | count

What I want to achieve using python is:

  • Add username to table, if does not exist, and set count to 1.
  • Whenever the username exists, increment count by 1.

What is the best approach for this using MySQLdb in python 2.7

Of course I could do this by querying for username, then if exists update count, but maybe there is a better way of doing this.

Thanks !

1
  • This will be of use to you. Commented Jun 24, 2013 at 23:40

1 Answer 1

1

Here is an approach using the link that @johnthexii provided (demo) (it is using just MySQL, so it isn't Python specific)

CREATE TABLE UserNames (`username` varchar(35) unique, `duplicates` int);

INSERT INTO UserNames (`username`, `duplicates`)
 VALUES ('stackoverflow.com', 0);

INSERT INTO UserNames (`username`, `duplicates`)
 VALUES ('dba.stackexchange.com/', 0)
 ON DUPLICATE KEY UPDATE `duplicates` = `duplicates`+1;

INSERT INTO UserNames (`username`, `duplicates`)
 VALUES ('stackoverflow.com', 0)
 ON DUPLICATE KEY UPDATE `duplicates` = `duplicates`+1;

Here is a breakdown of what is going on: The username field is marked as unique so any attempt to insert a record with an existing username will fail at the database level. Then the INSERT statement has an extra

ON DUPLICATE KEY UPDATE `duplicates` = `duplicates`+1

This tells MySQL that instead of failing the INSERT to just take the duplicates column and increment by one. When you run the three INSERT commands you will see two records, stackoverflow.com has a duplicates value of 1, while dba.stackexchange.com has a duplicates value of 0.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.