简体   繁体   中英

Insert, Replace/Update JDBC

I want to have a database where the votes of all users are stored. As an example, let's say user ABC chooses X on question Y. Then the same user ABC decides to vote on a separate question, and chooses V on question Z. The information is added to the database each time the user is pressing the submit button. Let's say that after a few days, the same user ABC decides to change one of its votes, so he goes back to question Y but chooses W this time, instead of X. A new entry should be avoided, and instead, the old one should be updated with the new choice.

My Votes table holds all the votes and users and all the choices:

CREATE TABLE Votes(
  id integer,
  username varchar(16),
  option varchar(16)
)

I've tried different methods each without success.

Before you start implementing these types of database connections its always good practice of thinking of a diagram to help you underatand how to organize your database tables. The relational modle is a great and simple way to start. You have to see what type of entities you have, in this case it is user and question. These entities will each represent a table. A user votes on a question and since many users can vote on each question and each user can vote on many questions the relationship between those entities "vote" also has to have a table. Ao we have 3 tables. The user table should have its id and user data you think is apropriate with id being its primary key. The question table ahould have its id and user data you believe to be apropriate with its id as primary key. And on the vote table you should have the id of user and the id of the question it was voted on with any other data you wich to have there. The user id and question id will form a comppsed primary key here. This way by acessing the vote table you will be able to know wich user voted on each question and, wich question was voted by wich user, etc...

I think you should add one more field to table for question.

When you do this in your app/database you should check if this user have a row with question and answer, if yes then update table or insert into if the row doesnt exits.

Change your table as below:
CREATE TABLE votes ( id bigint(20) NOT NULL AUTO_INCREMENT, user_id bigint(20) DEFAULT NULL, question_id bigint(20) DEFAULT NULL, option varchar(255) DEFAULT NULL, PRIMARY KEY (id), UNIQUE KEY user_id (user_id,question_id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8

Before you insert an new record, you should check if the user has answered this question by
select * from votes where user_id = ? and question_id = ? limit 1

If there is an record exists, update it, or insert an new record;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM