2017-01-15 29 views
2

下面是我按下按鈕後得到的輸出,儘管我的SQL Server數據庫中確實存在EmployeeNumberDOBC#鏈接到SQL Server Express的錯誤輸出

我已經嘗試了很多次,無法找出導致錯誤輸出的問題。

Output from C#

謝謝你的幫助!

C#代碼:

private void btn_Click(object sender, EventArgs e) 
{ 
    string constring = ConfigurationManager.ConnectionStrings["FirstConnection"].ConnectionString; 

    SqlConnection con = new SqlConnection(constring); 

    SqlCommand cmd = new SqlCommand("spEmployeeC", con); 
    cmd.CommandType = CommandType.StoredProcedure; 

    cmd.Parameters.AddWithValue("@Employee", txtEmployee.Text); 
    cmd.Parameters.AddWithValue("@DOB", txtPassword.Text); 

    //cmd.IsValid 

    con.Open(); 

    cmd.ExecuteNonQuery(); 

    if (txtEmployee.Text == "@Employee" && txtPassword.Text == "@DOB") 
    { 
     MessageBox.Show("Welcome " + txtEmployee.Text); 
    } 
    else 
    { 
     MessageBox.Show("The Username or Password you entered is incorrect. Please try again"); 
    } 
} 

SQL Server存儲過程的代碼:

CREATE PROCEDURE spEmployeeC 
    @Employee INT, 
    @DOB DATE 
AS 
BEGIN 
    SET NOCOUNT ON; 

    DECLARE @Employee_check INT; 
    DECLARE @Password_check DATE; 

    SELECT * 
    FROM Employee_Table 
    WHERE [EMPLOYEE_NUM] = @Employee AND [DOB] = @DOB 
END 
+0

首先:http://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ – DavidG

+0

第二:你不會對結果做任何事情的存儲過程執行。你只是檢查,如果用戶名文本框中包含文本「@Employee」 – DavidG

+0

@DavidG大衛你好!感謝您的分享,有沒有更好的方法來改善我的代碼? :) – FredaC

回答

0

像這樣的事情會更好:

protected void btn_Click(object sender, EventArgs e) 
    { 
     if (string.IsNullOrEmpty(txtEmployee.Text)) 
     { 
      MessageBox.Show("You must supply an Employee Number"); 
      return; 
     } 

     if (string.IsNullOrEmpty(txtPassword.Text)) 
     { 
      MessageBox.Show("You must supply a Password"); 
      return; 
     } 

     if (IsAuthenticated()) 
     { 
      MessageBox.Show("Welcome " + txtEmployee.Text); 
     } 
     else 
     { 
      MessageBox.Show("The Username or Password you entered is incorrect. Please try again"); 
     }; 
    } 

    private bool IsAuthenticated() 
    { 
     using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)) 
     { 
      SqlCommand cmd = new SqlCommand("spValidateCredentials", conn); 
      cmd.CommandType = CommandType.StoredProcedure; 
      cmd.Parameters.Add("@Employee", SqlDbType.Int).Value = txtEmployee.Text; 
      cmd.Parameters.Add("@DOB", SqlDbType.Date).Value = DateTime.Parse(txtPassword.Text); 
      conn.Open(); 
      return ((int)cmd.ExecuteScalar() > 0); 
     } 
    } 

而且可能更改存儲過程返回一個記錄數:

CREATE PROCEDURE [dbo].[spValidateCredentials] 
    @Employee INT, 
    @DOB DATE 
AS 
BEGIN 
    SELECT COUNT(*) 
     FROM Employee_Table 
    WHERE [email protected] 
     AND [email protected] 
END 
相關問題