2014-01-18 48 views
0

我有一個註冊從jsp與兩個字段的用戶名和密碼我在數據庫中插入這些字段。插入之前我想檢查用戶名是否已經存在,那麼不要在db中插入並打印任何含義的完整信息。如何匹配jsp數據庫中的字段值?

這裏是我的代碼:

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","[email protected]"); 
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
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","[email protected]"); 
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()); 
} 
相關問題