2015-11-19 15 views
-1

美好的一天,我有这个方法的问题,由于某种原因,它给了我一个错误。 “Java.sql.SqlException:语句未执行”。但它会检查该值是否重复,并按照以下方法提示错误。这阻止了我的注册完成。感谢您的帮助如何使用mysql和java验证用户名值,以避免重复的用户名

public static void UserExists(String y){ 

       try{ 

       query = " select * from MailRegister where Username=?"; 
       pst = connect.prepareStatement(query); //passes my query to java predefined prepared statement 
       pst.setString(1, Username.getText()); //passes the value of the username to the prepared statement 
       rs = pst.executeQuery(); //this would execute the query passed in the prepared statement 
       if(rs.next()){ 
        JOptionPane.showMessageDialog(null, " Sorry This Username is Taken"); 
       } 
        pst.close(); 
       rs.close(); 


       }catch(Exception e){ 
        JOptionPane.showMessageDialog(null, e);//shows error dialog 
       } 

      } 
+3

你得到的完整堆栈跟踪是...? 'connect'从哪里来?尝试发布一个自带的可运行的代码示例,其中包含有问题以及所获得的完整错误。谢谢。 – Taylor

+0

好吧,让我粘贴一个完整的可运行代码来解决这个问题。 – kashymeh

回答

0

您可能会收到此错误,因为您的对象始终没有正确关闭。你的connect正在打破。当需要防止泄漏时,一个好的做法是打开和关闭连接。

在上面的代码中,pst.close();rs.close();应该在finally中。

或者更清洁,准备的语句应该去里面:

try (pst = connect.prepareStatement(query)) {...} 

你不必这样,自己将其关闭,JVM将处理它。

+0

感谢您的信息,非常感谢,我会尝试一下并回复给您@Guillaume – kashymeh

+0

作为一个方面说明,您还应该在数据库中使用指向您的用户名列的唯一索引强制执行此规则。 –

相关问题