2016-09-08 9 views
-1

私は簡単な病院管理システムを作成していますが、データベースに接続する際に問題がありました。WPF C#でエラーが発生しましたログインフォーム

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 
using System.Data.Sql; 
using System.Data.SqlClient; 
public partial class Login : System.Web.UI.Page 
{ 
SqlConnection connectionstring = new SqlConnection("Server=.\\SQLEXPRESS;Database=TestDB;User Id=test; Password = woooow; "); 



protected void Button1_Click1(object sender, EventArgs e) 
{ 
    string cmdText = "SELECT 1 FROM Login WHERE Username = '" + TextBox1.ToString() + "' AND Password = '" + TextBox2.toString()+ "'"; 

    // using (SqlConnection cnn = new SqlConnection("Server=.\\SQLEXPRESS;Database=TestDB")) 
    using (SqlCommand SelectCommand = new SqlCommand(cmdText, connectionstring)) 
    { 
     SqlDataReader myReader; 
     connectionstring.Open(); 
     myReader = SelectCommand.ExecuteReader(); 
     int count = 0; 

     while (myReader.Read()) 
     { 
      count = count + 1; 
     } 

     if (count == 1) 
     { 
      //open form 
     } 
     else 
     { 

     } 
    } 

} 

}

これは私が通常のC#アプリケーションにログインフォームに使用するコードです。 TextBox1.toString()とTextBox2.toString()で何か問題があるように見えます。 テキストボックスの正確な値を取得するにはどうすればよいですか?グーグルで周りを回って、私はそれを言う多くの記事を見たが、すべてがお互いに異なっていると私は本当にそれについて混乱させる。

これを行う最善の方法は?

ありがとうございました。

+1

TextBox1.Text、しかし、より良いあなたはどのようにパラメータ – Steve

答えて

0

TextBox1.ToString()のTextBoxの内容を返します。正確なプロパティは、Textプロパティである

System.Windows.Forms.TextBox, Text: 

あるクラスのテキストボックスの完全修飾名を返し、しかし、単純に(あなたのTextBox1.ToStringを置き換える)のTextBox1と。テキストは、作業中に、他の潜在的でより危険なエラーの原因となる可能性があります。

SqlCommandは、パラメータコレクションを使用する必要があります。文字列を連結するSQLテキストは作成しないでください。これはよく(埋め込まれた引用符で小数、日付と文字列を解析する)エラーの原因と呼ばれる大きなセキュリティリスクとして知られているSql Injection.

は、代わりにパラメータを使用して、あなたのコードは、私も作った

public partial class Login : System.Web.UI.Page 
{ 
    private string conString = "Server=.\\SQLEXPRESS;Database=TestDB;User Id=test; Password = woooow; "; 

    protected void Button1_Click1(object sender, EventArgs e) 
    { 
     int count = 0; 
     string cmdText = @"SELECT 1 FROM Login 
          WHERE Username = @uname 
          AND Password = @pwd"; 

     using (SqlConnection cnn = new SqlConnection(conString)) 
     using (SqlCommand cmd = new SqlCommand(cmdText, cnn))  
     { 
      cnn.Open(); 
      cmd.Parameters.Add("@uname", SqlDbType.NVarChar).Value = textBox1.Text; 
      cmd.Parameters.Add("@pwd", SqlDbType.NVarChar).Value = textBox1.Text; 
      using(SqlDataReader myReader = SelectCommand.ExecuteReader()) 
      { 
       while (myReader.Read()) 
       count = count + 1; 
      } 
     } 
     if (count == 1) 
     { 
      //open form 
     } 
     else 
     { 

     } 
    } 
} 

お知らせです接続文字列がグローバルで、ローカルのSqlConnectionオブジェクトが作成されました。オブジェクトを確実に処分するには、最良の方法はすべてをローカルにして使い捨てオブジェクトをusingステートメントの中に置くことです。

パスワードを平文で保存することは、別のセキュリティリスクであることも考慮してください。この質問は説明しますThe Best way to store passwords in a database

関連する問題