如何在db中插入记录后从数据库中获取id

时间:2014-05-23 10:42:30

标签: java mysql servlets

如何使用JSP servlet从db获取id。这是我的JSP servlet代码,我需要通过警告消息框显示id的代码,在我的db中,我将id作为数据库中的自动增量。我这两天都在尝试这个。

如何在db?

中插入记录后从数据库中获取id

请帮我显示一个ID,例如“注册是suss-你的身份是.........”

package controller;

import java.io.IOException;
import java.io.PrintWriter;
javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
@WebServlet("/Register")
public class Register extends HttpServlet {

/**
 * 
 */
private static final long serialVersionUID = 2945154063362413961L;

/**
* @see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub

}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws          ServletException, IOException {
    // TODO Auto-generated method stub


        response.setContentType("text/html");  
       PrintWriter pw = response.getWriter(); 
        /*String fname=request.getParameter("firstname");
        String lname=request.getParameter("lastname");*/
        //pw.println("Firstname is" +fname);
        //pw.println("Firstname is" +lname);
        /*System.out.println("first=="+fname);
        System.out.println("last==="+lname);
        */


        //String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the          database  
        //Connection connection;  
        Connection conn=null;
        String url="jdbc:mysql://localhost:3306/";
        String dbName="Registrationform";
        String driver="com.mysql.jdbc.Driver";
        String dbUserName="root";
        String dbPassword="root";

    try{  
      String Fname = request.getParameter("firstname");  
      String Lname = request.getParameter("lastname");  
      String dob = request.getParameter("dob"); 
      String email= request.getParameter("email");    
      Class.forName(driver).newInstance();  
      System.out.println("welcome");

      conn = DriverManager.getConnection(url+dbName,dbUserName, dbPassword);
      System.out.println("Connection created");
      PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into event (firstname,lastname,dob,email) values(?,?,?,?)");//try2 is the name of the table  
      pst.setString(1,Fname);  
      pst.setString(2,Lname);        
      pst.setString(3,dob);
      pst.setString(4,email);
      int i = pst.executeUpdate();
     System.out.println("Query updated");
     PreparedStatement pstr =(PreparedStatement) conn.prepareStatement("select * from event(id);");//try2 is the name of the table  
     //conn.commit(); 
      String msg=" ";
      if(i!=0){  
        msg="You Are Succesfully Register For The Event Meet";
        //alert("You Are Succesfully Register For The E;vent Meet")
       // response.sendRedirect("reg.jsp");
        pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");  


      }  
      else{  
        msg="Failed to insert the data";
        pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
       }  
      pst.close();
    }  
    catch (Exception e){  
      pw.println(e);  
    }  

    }

    }





 java script code

   <%@ page language="java" contentType="text/html; charset=UTF-8"
   pageEncoding="UTF-8"%>

   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"        "http://www.w3.org/TR/html4/loose.dtd">
  <html>
  <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <link rel="stylesheet" type="text/css" href="reg.css">
  <title>Event Registration From</title>
 </head>

 <body class= "main">

<script type="text/javascript">

function register(registerform)
{

 if(registerform.firstname.value == "") {
 alert("Please enter your Firstname");
 registerform.firstname.focus();
 return false;
  }
 if(registerform.lastname.value == "") {
 alert("Please enter your Lastname");
 registerform.lastname.focus();
 return false;
 }
 if(registerform.dob.value == "") {
 alert("Please select your DOB");
 registerform.dob.focus();
 return false;
 }
 if(registerform.email.value == "") {
 alert("Please enter your Email-id");
 registerform.email.focus();
 return false;
 }
 /* var x=document.forms["form"]["email_id"].value;
 var atpos=x.indexOf("@");
 var dotpos=x.lastIndexOf(".");
 if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
 {
 alert("Not a valid e-mail address");
 return false;
 } */


  return true;
   }
  </script>

<form name="registerform" action ="Register" method = "post">
<div>
  <h3> Event Registration Form </h3>
  <div>
  <label for ="first" class ="label" > First Name </label>
  <input type="text" id="first" name="firstname" class="text" />
  </div>
  <div>
  <label for ="last" class ="label">Last Name</label>
  <input type="text" id="last" name="lastname" class="text">
  </div>
  <div>
   <label for ="dob" class ="label">Date Of Birth </label>
   <input type="text" id="dob" name="dob" class="text">
   </div>
   <div>
   <label for ="email" class ="label">Email_Id</label>
    <input type="text" id="email" name="email" class="text">
    </div>

 <div><input type="submit" value ="submit" class="button"  onclick="register(registerform)"></div>
  </div></form>







  </body>
  </html>

2 个答案:

答案 0 :(得分:1)

你可以尝试使用MySQL这样的东西:

        PreparedStatement ps = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS); 

        // Get generated key.
        ps.executeUpdate();
        ResultSet rs = ps.getGeneratedKeys();
        if (rs.next()) {
            int key = rs.getInt(1);
        }

其中ps是PreparedStatement,您从ResultSet对象中检索键。

答案 1 :(得分:0)

要获取上次生成的自动增量ID,可以使用MySql函数LAST_INSERT_ID()

另一种选择是使用MAX聚合函数返回id字段的最大值。由于上次插入的ID始终为最大MAX(id)

因为这是一种标准方式,所以这已被添加到常量中,所以这样做:

PreparedStatement ps = con.prepareStatement(YOUR_SQL, Statement.RETURN_GENERATED_KEYS);

对于某些像JDBC这样的JDBC驱动程序,您必须明确指定列:

PreparedStatement ps = con.prepareStatement(YOUR_SQL, new String[]{"USER_ID"});