2013-09-06 2 views
0
public bool ValidateUser(string uName) 
{ 
    SqlCommand cmd = new SqlCommand(); 
    if (connection == null) 
    { 
    connection = connectToDB(); 
    } 
    cmd.Connection = connection; 
    cmd.CommandText = "Select * from Users where UserName='" + uName + "'"; 
    cmd.CommandType = CommandType.Text; 
    SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
    if (dr.Rows.Count > 0) 
    { 
    return true; 
    } 
    else 
    { 
    return false; 
    } 

데이터 액세스 계층에 코드를 작성했지만 행 수를 계산할 때 오류가 발생했습니다.SqlDataReader의 행 누락 속성이 누락되었습니다.

오류 :

'System.Data.SqlClient.SqlDataReader' does not contain a definition for 'Rows' and no extension method 'Rows' accepting a first argument of type 'System.Data.SqlClient.SqlDataReader' could be found (are you missing a using directive or an assembly reference?)

+2

어떤 오류가 발생 했나요? –

+0

오류 'System.Data.SqlClient.SqlDataReader'에 '행'및 확장 메서드 정의가 없습니다. 'System.Data.SqlClient.SqlDataReader'형식의 첫 번째 인수를 수락하는 '행'을 찾을 수 있습니다. using 지시문이나 어셈블리 참조가 누락 되었습니까?) –

답변

3

사용 HasRows의 HasRows 속성을 고려한다. 대신 수를 원하는 경우

if (dr.HasRows) 
{ 
    return true; 
} 

그러나, 당신은 SqlDataReader 개체에 행 속성이 없습니다 데이터 테이블

DataTable dt = new DataTable(); 
dt.Load(dr); 
int num = dt.Rows.Count; 
1

에로드 할 수 있습니다.
그러나 코드에는 많은 문제가 있습니다.

public bool ValidateUser(string uName) 
    { 
     using(SqlConnection cn = connectToDB()) 
     using(SqlCommand cmd = new SqlCommand("Select count(*) from Users where [email protected]", cn)) 
     { 
      cmd.Parameters.AddWithValue("@name", uName); 
      return (Convert.ToInt32(cmd.ExecuteScalar()) > 0) 
     } 
    } 
  • 연결 개체가 더 이상 글로벌없고 그것은 사용 문의 폐쇄에 파괴 :
    나는 이런 식으로 코드를 변경합니다.
  • DataReader를 사용할 필요 사용자가 글로벌 연결 개체를 피 입력 데이터

에 SQL 주입을 방지하기 위해 매개 변수가있는 쿼리를 사용 하지

  • 존재하는 경우, 또는 그냥 찾습니다. connection pooling 인프라는 성능 문제를 제거하고 과도한 리소스 사용으로부터 안전합니다.
    SqlDataReader는 많은 레코드를 순차적으로 검색해야하지만 사용자가 존재하거나 최선의 방법이 아닌 경우 정보를 얻으려면 ExecuteScalar 메서드와 적절한 sql을 사용하는 것이 좋습니다.
    매개 변수가있는 쿼리는 모든 중요한 데이터베이스 작업에 필수 항목입니다. 프레임 워크에 입력 내용의 형식을 지정하는 작업이 전달되어 위험하지는 않습니다. Sql Injection

  • 관련 문제