我希望在注册时不要多次使用特定的电子邮件 ID。这是我的代码:
if(request.getParameter("btn1")!=null)
{
String unm=request.getParameter("nm");
String em=request.getParameter("email");
String pwd=request.getParameter("pass");
Connect c1=new Connect();
String q="insert into register(name,email,password) values('"+unm+"','"+em+"','"+pwd+"');";
int rs=c1.DMLExecuter(q);
if(rs>0)
%>
<script>
alert("You are registered now. Please login to continue.");
</script>
我应该如何检查电子邮件 ID 是否被使用两次?
最佳答案
确保您的电子邮件字段是唯一的,例如通过相应地调整 DDL(这将使数据库确保电子邮件地址是唯一的)。或者,可以将电子邮件字段设为主键:
CREATE TABLE register( ... EMAIL VARCHAR(50) NOT NULL UNIQUE, ... )
在代码中,插入之前,检查该 ID 的现有电子邮件数量:
long existingCount = ... String countQuery = "SELECT COUNT(1) FROM register WHERE email = ?"
使用 request.getParameter("email")
的值运行此查询。
结果应该是一个数字,告诉您使用该电子邮件的现有用户数量。
假设计数已存储在 existingCount
变量中:
if(existingCount == 0) {
//Put here the code to insert the new user as shown in your question...
} else {
%>
<script>
alert("You are already registered. Login or choose a different email");
</script>
<%
}
请注意,我的sql使用了绑定(bind)变量,请使用准备好的语句
关于java - 使用 JSP 检查数据库中是否已存在电子邮件 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37436354/