Solved

JDBC: mySQL: How do I autoincrement the primary key?

Posted on 2004-08-09
5
2,443 Views
Last Modified: 2008-01-09
JDBC: mySQL: How do I autoincrement the primary key?

Here is my table:

CREATE TABLE rtpm_user (
  rtpm_user_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  firstname VARCHAR(20) NULL,
  surname VARCHAR(20) NULL,
  username VARCHAR(20) NULL,
  password1 VARCHAR(15) NULL,
  password2 VARCHAR(15) NULL,
  email VARCHAR(15) NULL,
  sdp_code VARCHAR(5) NULL,
  last_access DATE NULL,
  PRIMARY KEY(rtpm_user_id)
);

Here is my database handler (it does not contain any statement for autoincrementing) as most of what I've tried has failed.

public class DBHandler extends HttpServlet {

    public void doPost (HttpServletRequest request,
      HttpServletResponse response) {
      try { // OBTAIN A DATABASE CONNECTION
         
          // Step 1: Load the JDBC driver          
          Class.forName("com.mysql.jdbc.Driver");
             
          // Step 2: Establish a connection to the database          
       
          Connection conn = DriverManager.getConnection(
          "jdbc:mysql://localhost/rtpmKenyaDB","rrugemalira", "Pacifier7");
 
          String sql = "INSERT INTO rtpm_user(firstname, surname, " +
          "username, password1, password2, email, " +
          "sdp_code) VALUES (?, ?, ?, ?, ?, ?, ?)";
          PreparedStatement ps = conn.prepareStatement(sql);
         
          // Retreave the bean properties to be inserted into table rtpm_user
          FormBean f = (FormBean) request.getAttribute("formHandler");
         
          // Set the parameters in the prepared statement
          ps.setString(1, f.getFirstName());
          ps.setString(2, f.getLastName());
          ps.setString(3, f.getUserName());
          ps.setString(4, f.getPassword1());
          ps.setString(5, f.getPassword2());
          ps.setString(6, f.getEmail());
          ps.setString(7, f.getSdp());
         
          // Insert the row in the table
          ps.executeUpdate();


          // Close the connection
          ps.close();
          conn.close();    
      }
      catch (SQLException e) {
          // handle any errors
          System.out.println("SQLException: " + e.getMessage());
          System.out.println("SQLState: " + e.getSQLState());
          System.out.println("VendorError: " + e.getErrorCode());
          }
      catch (Exception e) {
      e.printStackTrace();
      }
     
      // Send the request back to success.jsp  
      try {
          getServletConfig().getServletContext().
            getRequestDispatcher("/success.jsp").
             forward(request, response);
      }
      catch (Exception e){}
     
   }
}

Handler works fine for the first data entry into the database, where rtpm_user_id is automatically given the value 0.

A second data entry fails because rtpm_user_id is assigned the same value of 0. How do I autoincrement? Kindly instruct.
0
Comment
Question by:Rrugemalira
5 Comments
 
LVL 32

Expert Comment

by:ldbkutty
ID: 11757261
autoincrement should increment automatically... ;)
what is the exact error you got ? what DB do you use ?
0
 
LVL 32

Expert Comment

by:ldbkutty
ID: 11757280
>> Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/rtpmKenyaDB","rrugemalira", "Pacifier7");
oops... Ok..MySQL... :-D
0
 
LVL 9

Expert Comment

by:ronan_40060
ID: 11757806
hello Rrugemalira
and yes ldbkutty nice to hear from :) and good to have u here in JSP :)
well yes in ur SQL create table
>>>> rtpm_user_id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
should increment
Like ldbkutty said what kinda error messages you are getting , pls post
waiting for ur reply
regards
ronan
 
0
 

Author Comment

by:Rrugemalira
ID: 11758282
Here's the error message:

SQLException: Duplicate key or integrity constraint violation,  message from server: "Duplicate entry '0' for key 1"
SQLState: 23000
VendorError: 1062
0
 
LVL 11

Accepted Solution

by:
sompol_kiatkamolchai earned 500 total points
ID: 11758767
Try to change INTEGER datatype to bigint or mediumint
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

In  today’s increasingly digital world, managed service providers (MSPs) fight for their customers’ attention, looking for ways to make them stay and purchase more services. One way to encourage that behavior is to develop a dependable brand of prod…
Use of TCL script on Cisco devices:  - create file and merge it with running configuration to apply configuration changes
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

757 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now