Home > front end >  java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'null' for key 'lo
java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'null' for key 'lo

Time:12-31

When I try to insert the data in database table it gives me error "java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 'null' for key 'login.PRIMARY'". It duplicates the null column underneath the entered data. It gives me the error on line " stmt.executeUpdate(sql);"

<%@ page import = "java.sql." %>
<%@ page import = "javax.sql.
" %>

<%
    Class.forName("com.mysql.jdbc.Driver");
    String url       = "jdbc:mysql://127.0.0.1:3306/?user=root";
    String user      = "root";
    String pass      = "root";
    String firstname = request.getParameter("firstname");
    String lastname  = request.getParameter("lastname");
    String email     = request.getParameter("email");
    String pass1     = request.getParameter("pass");
    
    Connection con = DriverManager.getConnection(url, user, pass);
    Statement stmt = con.createStatement();

    
   String sql = "INSERT INTO facebook.login (firstname, lastname, email, password) VALUES('" firstname "','" lastname "','"  email  "','"  pass1  "');";
  

    stmt.executeUpdate(sql);
    stmt.close();
    con.close();


%>

CodePudding user response:

You did not include a value in the insert statement the value for login.PRIMARY column which happens to be a non duplicate column and it is possible that there's already a record with a null value for login.PRIMARY column that's why this error was encountered.

I suggest that you define a unique value for login.PRIMARY column in your INSERT statement or update your table structure for the login.PRIMARY to make it auto increment.

You can refer to below link on how to implement auto increment in a table.

https://www.w3schools.com/sql/sql_autoincrement.asp

CodePudding user response:

The problem is that you are trying to insert with duplicate (key already present in the table)primary key.

Your table might have accepted "null" as PK for one of the row , now again program trying to set null as PK which is already present in table.

You can use auto increment of PK if it's a number else in your case use PK on "email" bcz in real life scenario two email strings cannot be same.

  • Related