Solved

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

Posted on 2004-08-09
5
2,445 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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
java.util.concurrent.Callable way of creating threads 2 102
servlet init param and contect param 3 59
TreeSet comparator example 7 90
withoutString  challenge 40 182
Cloud-based technologies and services will continue to grow in popularity in 2017 thanks to the simple, scalable and cost-effective solutions they deliver. Here are three areas where cloud adoption is poised to really take off.
With the rapid rise in mobile usage, mobile devices are here to stay and have become an integral part of doing business. Here are 9 great apps for your BYOD environment.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).

910 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

18 Experts available now in Live!

Get 1:1 Help Now