2012-04-14 9 views
0

JavaでログインUIを構築しようとしています。しかし、私のSQL認証JavaでのSQL認証によるログイン

の問題は、ここでは、コードがありますされています

public void actionPerformed(ActionEvent e){ 
      if (e.getSource() == Login) 

        try { 
       Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
       Connection con=DriverManager.getConnection("jdbc:odbc:MessageStore","sa","12345"); 
       Statement cmd=con.createStatement(); 
       ResultSet rs=cmd.executeQuery("select * from UserList where UserName='"+nameText.getText()); 
    } 

しかし、「RS」との警告があります: ローカル変数rsの値は

どのように使用されていませんこの問題を解決するために?

また、SQL認証を実装するためのより簡単なコードがありますか?

は、メッセージを無視するか、それに割り当てを削除するかを選択することができ、「変数Xの値が使用されていない」のほとんどのケースでは、あなたに

+1

データベース値がResultSetから取得することができますが、それを反復処理する必要があります。 –

+1

これはSQLインジェクションにはオープンです。文字列をエスケープするか、またはプリペアドステートメントを使用する必要があります。また、あなたはrsを使用していないので、警告が発生しています。 rsを使用しない場合は、rsに戻り値を割り当てないでください。ただし、行が存在するかどうかを確認するために、またはパスワードが正しいかどうかを確認するために使用する必要があるため、使用する必要があります。また、人々がSQLサーバーに直接接続できるようにすることについては注意が必要です。あなたがそうすることを期待していない人があなたのアプリケーションの外でそれに接続すると、それはセキュリティ上の問題となります。 – Corbin

答えて

1

ありがとうございます。そのような場合、あなたは値を何もしません。

しかし、この場合、データベースに対してのみクエリを実行しますが、結果に対しては何も実行しません。したがって、検証しようとしているユーザーが実際に有効なユーザーかどうかは分かりません。

したがって、実際に結果があり、ユーザーがログインできるかどうかを確認するには、変数 "rs"を使用する必要があります。

public void actionPerformed(ActionEvent e){ 
    if (e.getSource() == Login){ 
    try { 
     Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // may not be needed since JDBC4 
     Connection con=DriverManager.getConnection("jdbc:odbc:MessageStore","sa","12345"); 
     PrePareStatement cmd=con.prepareStatement("select * from UserList where username=?"); // safer, protect against 
     cmd.setString(1,nameText.getText()); 
     ResultSet rs=cmd.executeQuery(); 
     if(rs.next()){ 
     // username does exist, now check the password 
     }else{ 
     // username does not exist 
     } 
    }catch(Exception e){} 
    } 
} 
+0

OPのポストでの文字列の連結は悪い習慣であるため、[Prepared Statement](http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html)がぴったり含まれています。 SQLインジェクションのために安全ではありません。 – hamena314

0

グローバル変数としてResultSetを作成します。

public void actionPerformed(ActionEvent ae) { 
if (ae.getSource() != null) { 
String connectionUrl = "jdbc:sqlserver://localhost:1420;" + "databaseName=TestsampleDB1;"; 
Connection con = null; 
Statement stmt = null; 
ResultSet rs = null; 
try { 
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); 
    System.out.println("Driver okay"); 
    con = (Connection) DriverManager.getConnection("jdbc:odbc:MessageStore", "sa", "12345"); 
    System.out.println("Connection Made"); 
    PreparedStatement cmd = con.prepareStatement("select * from UserList where username=?"); 

    if (rs.next()) { 
     // login user exist 
    } else { 
    // user doesn't exist} 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
    } 

}}

関連する問題