2011-12-21 2 views
0

다음은 열 nos에서 개수를 가져 오는 데 사용하는 코드입니다. 여기SQL 서버에서 count() 사용

//get max count of orders on server .2 
    public int getmaxcountfornos(string caseno,TextBox TextBox3) 
    { 
     int count2 = 0; 
     try 
     { 
      String dd_webCofig = ConfigurationManager.ConnectionStrings["counton140"].ConnectionString; 
      OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig); 
      ddlistconn.Open(); 

      string cnt_2 = "select count(nos) from training_jud.orders where [email protected] and [email protected]"; 
      OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

      ddlistCmd_2.Parameters.AddWithValue("b", caseno); 
      ddlistCmd_2.Parameters.AddWithValue("c", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

      count2 = (int)ddlistCmd_2.ExecuteScalar(); 
     } 

     catch (Exception ee) 
     { 
      HttpContext.Current.Response.Write(ee.Message); 
     } 
     return count2; 
    } 

내가

지정한 캐스트로 예외를 얻고 유효하지 않습니다.

누구든지이 문제를 해결할 수 있습니까? 대신

count2 = (int)ddlistCmd_2.ExecuteScalar(); 

의 전술 한 사용은

답변

1

이 시도 :`의 결과가 ExecuteScalar`가 아닌

//get max count of orders on server .2 
public int getmaxcountfornos(string caseno,TextBox TextBox3) 
{ 
    int count2 = 0; 
    try 
    { 
     String dd_webCofig = ConfigurationManager.ConnectionStrings["counton140"].ConnectionString; 
     OdbcConnection ddlistconn = new OdbcConnection(dd_webCofig); 
     ddlistconn.Open(); 

     string cnt_2 = "select count(nos) from training_jud.orders where [email protected] and [email protected]"; 
     OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

     ddlistCmd_2.Parameters.AddWithValue("**@b**", caseno); 
     ddlistCmd_2.Parameters.AddWithValue("**@c**", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

     count2 = **Convert.ToInt32**(ddlistCmd_2.ExecuteScalar()); 
    } 

    catch (Exception ee) 
    { 
     HttpContext.Current.Response.Write(ee.Message); 
    } 
    return count2; 
} 
0
count2 = int.Parse(ddlistCmd_2.ExecuteScalar().ToString()); 

문제를 해결했다.

+1

아마 때문에 int. 길거나 uint 일 수 있습니다. 이 경우 캐스트가 작동하지 않습니다. 문자열을 통해 가면 (그 일을하지 마십시오) 문제를 해결할 수 있습니다. 실제로 쿼리를 실행하여 반환 된 유형을 확인하십시오. –

0

지금까지 코드 그러나 당신이 코드 부분 아래에보십시오 것, 좋은 것입니다, 감사

string cnt_2 = "select count(nos) as OrderCount from training_jud.orders where [email protected] and [email protected]"; 
OdbcCommand ddlistCmd_2 = new OdbcCommand(cnt_2, ddlistconn); 

ddlistCmd_2.Parameters.AddWithValue("@b", caseno); 
ddlistCmd_2.Parameters.AddWithValue("@c", Convert.ToDateTime(TextBox3.Text).ToString("yyyy-MM-dd")); 

count2 = Convert.ToInt32(ddlistCmd_2.ExecuteScalar());