简体   繁体   中英

Java & MySQL - Unique Key not working?

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

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.

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