registration.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author srini
*/
@WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequset (request,response);
}
public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String phone =request.getParameter("phone");
String username =request.getParameter("uname");
String password =request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt=con.prepareStatement(
"insert into headwy(phone,uname,pass) values(?,?,?)");
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
int i=pstmt.executeUpdate();
if(i>0)
out.print("You are successfully registered...");
pstmt.close();
con.close();
}
catch (Exception e2) {System.out.println(e2);
}
out.close();
}
}
我在插入数据之前尝试检查数据库中的现有数据。
但我不知道如何在servlet程序中执行两个SQL语句。
因为我第一次使用sql和servlet。
请提供解决方案,或者告诉我如何查看数据库中现有数据的想法。
答案 0 :(得分:0)
=&GT;制作如下样本的存储过程,然后使用java代码调用并将结果输出到输出参数。
CREATE PROCEDURE InsertName
(
@username varchar(25),
@userpassword varchar(25)
)
AS
IF EXISTS(SELECT 'True' FROM MyTable WHERE username = @username)
BEGIN
--This means it exists, return it to ASP and tell us
SELECT 'This record already exists!'
END
ELSE
BEGIN
--This means the record isn't in there already, let's go ahead and add it
SELECT 'Record Added'
INSERT into MyTable(username, userpassword)
VALUES(@username,@userpassword)
END