2012-03-02 47 views
0

我需要能夠驗證一個用戶名和密碼對sql服務器,我需要一個C#表單應用程序的代碼。如何將SQL身份驗證添加到C#表單應用程序?

我有2個文本框(1個用戶和1通)設置,然後我有一個登錄按鈕。

  SqlConnection UGIcon = new SqlConnection(); 
     UGIcon.ConnectionString = "Data Source=HP-PC//localhost;Initial Catalog=UGI;Integrated Security=True"; 
     UGIcon.Open(); 

     string userText = textBox11.Text; 
     string passText = textBox12.Text; 

     SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword FROM LoginDetails WHERE stUsername='" + textBox11.Text + "' and stPassword='" + textBox12.Text + "'", UGIcon); 
     SqlDataAdapter da = new SqlDataAdapter(cmd); 
     DataTable dt = new DataTable(); 
     da.Fill(dt); 

     if (dt.Rows.Count > 0) 
     { 
      MessageBox.Show("Login Success!!"); 
      cmd = new SqlCommand("SELECT stRole from LoginDetails where [email protected]", UGIcon); 
      cmd.Parameters.AddWithValue("@stUsername",userText); 
      string role = cmd.ExecuteScalar().ToString(); 
      MessageBox.Show(role); 
      UGIcon.Close(); 
     } 
     else 
     { 
      MessageBox.Show("Access Denied!!"); 
      UGIcon.Close(); 
     } 
+0

的onclick作出的SqlConnection和一個SqlCommand和查詢您的數據庫,並得到一個SqlDataReader可以讀取和驗證用戶 – f2lollpll 2012-03-02 05:35:45

+0

你嘗試過什麼?在SO上說「_I需要代碼... ...」通常是不可接受的。我們在這裏幫助你,而不是爲你做你的工作。 – 2012-03-02 05:37:19

+0

只是將它添加到操作。 – 2012-03-02 05:41:31

回答

1

我是一個真正的信徒在使用 「使用」 的語句。您也可以通過在原始查詢中詢問stRole變量來保存第二個查詢。使用塊會自動處理對象,所以當執行離開這個區域時,對象會自動清理。

using (SqlConnection UGIcon = new SqlConnection("Data Source=localhost\\sqlexpress;Initial Catalog=UGI;Integrated Security=True")) 
     { 
      UGIcon.Open(); 

      string userText = textBox11.Text; 
      string passText = textBox12.Text; 

      SqlCommand cmd = new SqlCommand("SELECT stUsername,stPassword, stRole FROM LoginDetails WHERE stUsername='" + userText + "' and stPassword='" + passText + "'", UGIcon); 

      using (SqlDataReader rdr = cmd.ExecuteReader()) 
      { 
       if (rdr.HasRows) 
       { 
        while (rdr.Read()) 
        { 
         string role = rdr["stRole"].ToString(); 
         MessageBox.Show(role); 
        } 
       } 
       else 
       { 
        MessageBox.Show("Access Denied!!"); 
       } 
      } 
     } 
0

請選中該代碼

SqlConnection thisConnection = new 
     SqlConnection(@"Server=(local)\sqlexpress;Integrated Security=True;" + 
        "Database=northwind"); 
     thisConnection.Open(); 
     SqlCommand thisCommand = thisConnection.CreateCommand(); 
     thisCommand.CommandText = "Select count(*) from UserDetails 
WHere UserName = "+txtUsername.text.trim().toLower() + " and Password = " +txtPassword.text.trim().toLower(); 
     Object countResult = thisCommand.ExecuteScalar(); 
     Console.WriteLine("Count of Customers = {0}", countResult); 

     thisConnection.Close(); 
+0

我正在使用表單應用程序而不是控制檯應用程序,並且我在哪裏添加遠程地址的IP,我只是替換(本地)? – 2012-03-02 05:50:21

+0

@John_Dong - 在這個答案中提供的代碼可以很容易地適應WinForms。 – 2012-03-02 05:53:10

+0

是啊,我只是注意到你碰巧有SQL查詢發送到SQL服務器添加用戶和密碼的任何機會? – 2012-03-02 05:56:44

相關問題