我在jsp中注册了两个字段用户名和密码我在数据库中插入这些字段。在插入之前我想检查用户名是否已经存在,然后不要在db中插入并打印任何含义完整的消息。
这是我的代码:
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Court","root","Dan@1234");
PreparedStatement ps=cn.prepareStatement("insert into Councel values(?,?)");
ps.setString(1,user);
ps.setString(2,pass);
int i=ps.executeUpdate();
if(i==1)
}
catch(Exception e)
{
out.println(e.toString());
}
答案 0 :(得分:1)
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Court","root","Dan@1234");
PreparedStatement ps0=cn.prepareStatement("Select uname from Councel where uname=?");
ps0.setString(1,user);
ResultSet rs=ps0.executeQuery();
if(rs.next())
{
//User already exists
}
else{
PreparedStatement ps=cn.prepareStatement("insert into Councel values(?,?)");
ps.setString(1,user);
ps.setString(2,pass);
int i=ps.executeUpdate();
if(i==1){}
}
}
catch(Exception e)
{
out.println(e.toString());
}