如何在jsp中匹配数据库中的字段值?

时间:2014-01-18 07:00:12

标签: jsp jdbc

我在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());
                    }

1 个答案:

答案 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());
}