如何在此代码中找到数据库中的现有用户名,因为我是这种语言的新手,请你帮助我....
<%@page import="java.sql.Statement"%>
<%@page import="pack.Db"%>
<%@page import="java.sql.Connection"%>
<%
String name = request.getParameter("name");
String pass = request.getParameter("pass");
String role = request.getParameter("role");
String gender = request.getParameter("gender");
String age = request.getParameter("age");
String email = request.getParameter("email");
String date = request.getParameter("date");
try {
Connection con = Db.getConnection();
Statement st = con.createStatement();
int i = st.executeUpdate("insert into data values('" + name + "','" + pass + "','" + role + "','" + gender + "','" + age + "','" + email + "','" + date + "','NO','Waiting')");
if (i != 0) {
response.sendRedirect("signup.jsp?Registration Successfully");
} else {enter code here
response.sendRedirect("signup.jsp?Registration Failed");
}
} catch (Exception e) {
System.out.println("Error in signupction" + e.getMessage());
}
%>
答案 0 :(得分:0)
在插入用户之前,您可以
1)通过从数据库中提取名称来检查用户名是否已存在
2)如果存在,则将错误发送到UI
3)如果不存在,请插入用户。
以下是代码段:
try {
Connection con = Db.getConnection();
Statement st = con.createStatement();
ResultSet result = stmt.executeQuery("select name from data where name='"+name+"'");
if(result.next())
{
response.sendRedirect("signup.jsp?Registration Failed");
}
else{
int i = st.executeUpdate("insert into data values('" + name + "','" + pass + "','" + role + "','" + gender + "','" + age + "','" + email + "','" + date + "','NO','Waiting')");
if (i != 0) {
response.sendRedirect("signup.jsp?Registration Successfully");
}
else {
response.sendRedirect("signup.jsp?Registration Failed");
}
}
} catch (Exception e) {
System.out.println("Error in signupction" + e.getMessage());
}
答案 1 :(得分:0)
您可以尝试:
try {
Connection con = Db.getConnection();
Statement st = con.createStatement();
String sqlcommand = "SELECT * FROM data WHERE uname = " + name;
ResultSet rs = st.executeQuery(sqlcommand);
if(rs.next()){
response.sendRedirect("signup.jsp?Registration Failed");
}else{
int i = st.executeUpdate("insert into data values('" + name + "','" + pass + "','" + role + "','" + gender + "','" + age + "','" + email + "','" + date + "','NO','Waiting')");
if (i != 0) {
response.sendRedirect("signup.jsp?Registration Successfully");
}
}
} catch (Exception e) {
System.out.println("Error in signupction" + e.getMessage());
}