The prepared statement returns false, but is the row inserted?

So this is my table:

mysql> DESCRIBE app_user;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| username | varchar(40) | NO   | PRI | NULL    |                |
| password | varchar(40) | NO   |     | NULL    |                |
| email    | varchar(40) | NO   | PRI | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set

mysql> 

I expect that I could not add 2 lines with the same username, because the username is the primary key.

And this is my Java code:

@Test
public void shouldNotInsertWithSameUserName() throws IOException, SQLException {
    AppUserAccessObject appUserAccessObject = new AppUserAccessObject(new DatabaseConnectionImpl());
    Assert.assertFalse(appUserAccessObject.insertUser("koray", "email", "password"));
}

So this test passes, which means that insertUser returns false. However, when I check the database, I see a new line. What am I doing wrong? And the insert:

public boolean insertUser(String username,String email,String password) throws SQLException {
    PreparedStatement preparedStatement = connection.prepareStatement("INSERT INTO "+ tableName + "(username,email,password) VALUES(?,?,?)");
    preparedStatement.setString(1,username);
    preparedStatement.setString(2,email);
    preparedStatement.setString(3,password);
    boolean execute = preparedStatement.execute();
    return execute;
}
+4
source share
1 answer

Your primary key is based on three fields:

  • id (which matters auto increase)
  • Username
  • Email

, , 3 . id null, , .

id , Unique Key username email. : username email.

:

CREATE TABLE app_user (
    id INT PRIMARY KEY AUTO_INCREMENT,
    username varchar(40),
    password varchar(40),
    email varchar(40),
    UNIQUE KEY (username),
    UNIQUE KEY (email)
);

:


false, ?

PreparedStatement#execute javadoc:

: true, ResultSet; false, - - , .

false, (INSERT ).

+9

Source: https://habr.com/ru/post/1536627/


All Articles