2012-03-29 56 views
2

我需要從tbl_Ticket檢索TICKET_ID傳遞到發送電子郵件功能的主體部分.. 是下面的代碼是否正確? 每一個時代,我得到TICKET_ID 1 ..如何從函數中的select查詢返回int值?

public int select_TicketId(){ 
    string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString(); 
    SqlConnection sqlCon = new SqlConnection(strConn); 
    string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' "); 
    sqlCon.Open(); 
    SqlCommand cmd1 = new SqlCommand(getId, sqlCon); 
    int i=cmd1.ExecuteNonQuery(); 
    return i; 
} 

回答

2

你打電話ExecuteNonQuery。但這是一個查詢。這應該已經敲響了一些警鐘:)

嘗試ExecuteScalar代替,並把結果爲int ...

return (int) cmd1.ExecuteScalar(); 

請注意,您應該使用using語句命令和連接爲好,使兩者都適當關閉。

(我以前從來沒有發現這一點),你應該絕對使用參數化的SQL,而不是直接包括值到SQL的。否則,你打開SQL Injection attacks ...

因此,像:

private const string FetchTicketIdSql = 
    "select Ticket_Id from tbl_Ticket where Client_EmailAdd = @Email"; 

public int FetchTicketId() 
{ 
    // No need for ToString call... 
    string connectionString = 
     ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql)) 
     { 
      command.Parameters.Add("@Email", SqlDbType.NVarChar).Value = 
       bjNewTic_BAL.email; 
      return (int) command.ExecuteScalar(); 
     } 
    } 
} 

你應該考慮你什麼發生,如果不是正好有一個結果,但...

+0

謝謝你讓我試試這個:) – hks 2012-03-29 10:56:23

+0

感謝ü如此多的工程:) – hks 2012-03-29 11:57:07

5

您正在搜索返回第一個值的ExecuteScalar。

public int select_TicketId() 
     { 
      string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString(); 
      SqlConnection sqlCon = new SqlConnection(strConn); 
      string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' "); 
      sqlCon.Open(); 
      SqlCommand cmd1 = new SqlCommand(getId, sqlCon); 
      int i=Convert.ToInt32(cmd1.ExecuteScalar()); 
      return i; 

     } 

還可以使用CommandProperties設置where語句爲更好的安全性,如下圖所示:

public int select_TicketId() 
{ 
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString; 
    int result = -1; 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     SqlCommand command = new SqlCommand(); 
     command.Connection = connection; 
     command.CommandType = CommandType.Text; 
     command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where [email protected]"; 
     command.Parameters.Add("@email", SqlDbType.Text).Value = objNewTic_BAL.email; 
     result = Convert.ToInt32(command.ExecuteScalar()); 
    } 

    return result; 
} 
0

Hiral, 的ExecuteNonQuery在

int i=cmd1.ExecuteNonQuery(); 

將返回的滿足記錄數您的查詢。在這種情況下,它是1(或0如果沒有電子郵件)

嘗試使用的ExecuteReader代替。