0

I'm using the MySQL Workbench, and assigned one of my columns as a Unique Key. When I check the MySQL table, it still enters duplicates for "users_name" I'm still new to MySQL/Java, so I'm sure I'm just making a silly mistake.

System.out.print("Name: ");
String name = sc.nextLine();
System.out.print("Password: ");
String pass = sc.nextLine();

String SQL = String.format("INSERT INTO users (users_name, users_password) values('" + name + "','" + pass + "')");
PreparedStatement stmt = (PreparedStatement) connection.prepareStatement(SQL);
stmt.executeUpdate(SQL);

MySQL Table Definition:

CREATE  TABLE IF NOT EXISTS `mydb`.`users` (
`users_id` INT NOT NULL AUTO_INCREMENT ,
`users_name` VARCHAR(45) NULL ,
`users_password` VARCHAR(45) NULL ,
PRIMARY KEY (`users_id`) ,
UNIQUE INDEX `users_id_UNIQUE` (`users_id` ASC) ,
UNIQUE INDEX `users_name_UNIQUE` (`users_name` ASC) )
ENGINE = InnoDB
4
  • The important info would be your table definition Commented Mar 3, 2013 at 1:55
  • What do you mean by that? Sorry. Commented Mar 3, 2013 at 1:56
  • @JonathonCharlesLoch: It means please show the sql statment that created your table. something like: create table users(id int... Commented Mar 3, 2013 at 1:58
  • @juergend: Post it as an answer ;) Commented Mar 3, 2013 at 2:10

1 Answer 1

2

Not really an answer, but very helpful advice:

This is how you should use your PreparedStatement:

String sql = "INSERT INTO users (users_name, users_password) values (?, ?);";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, name);
stmt.setString(2, pass);
stmt.executeUpdate();

To answer your actual question, we need to see the table definition.

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

2 Comments

+1 definitely don't String-concat in the values of your PreparedStatement as OP has in the code snippet above.
Well, I made a new table, with the same Primary Keys, Uniques, Auto Increments, etc. And now it works. Guess something didn't work last time.

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.