2013-06-05 3 views
2
protected void populateDataGrid() 
{ 
    string connectionString = configurationManager.ConnectionStrings["myConnectionString"].ConnectionString; 
    string command = "select * from student"; 

    SqlDataAdapter dataAdapter = new SqlDataAdapter(command, connectionString); 
    DataSet data = new DataSet(); 

    dataAdapter.Fill(data); 
    GridView1.DataSource = data; 
    GridView1.DataBind(); 
} 

protected void Button2_Click(object sender, EventArgs e) 
{ 
    string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString; 
    string command = @"INSERT INTO [student] (studentID, studentFirstName, studentLastName) 
         VALUES (" + TextID.Text + ", '" + TextFirstName.Text + "', '" + TextLastName.Text + "')"; 
    SqlConnection sqlConnection = new SqlConnection(connectionString); 

    SqlCommand cmd = new SqlCommand(); 
    cmd.CommandType = System.Data.CommandType.Text; 
    cmd.CommandText = command; 
    cmd.Connection = sqlConnection; 

    sqlConnection.Open(); 
    cmd.ExecuteNonQuery(); 
    sqlConnection.Close(); 

    TextID.Text = ""; 
    TextFirstName.Text = ""; 
    TextLastName.Text = ""; 
    populateDataGrid(); 
} 

첫 번째 함수는 모든 테이블 데이터를 가져 와서 gridview에 덤프합니다. 두 번째 함수는 입력을 받아서 데이터베이스에 삽입합니다. 이러한 기능을 요약하거나 단순화 할 수있는 방법은 무엇입니까?SQL 연결을 사용하는 최적의 표준 방법은 무엇입니까?

+0

안녕하세요, 클래스 호출 학생을 만들고 거기에 연결 문자열을 비공개로두고 메소드를 삽입하고 메소드를 추가하십시오. 문자열 연결을 피하고 매개 변수를 @ –

+3

과 함께 사용하지 마십시오. 거기에 모든 db 함수가있는 dbhelper 클래스를 작성하고 학생 클래스에서 호출하십시오. –

답변

5

이러한 기능을 요약하거나 단순화 할 수있는 방법은 무엇입니까?

간단히하기 전에 정확성에 중점을 둡니다. 대신 SQL 자체에 가치를두기의

  • 당신이해야 절대적으로 사용 매개 변수화 된 SQL : 현재 내가 코드를 적어도 두 가지 문제를 볼 수 있습니다. 현재 코드는 SQL 삽입 공격에 취약합니다.
  • using 문을 사용해야 만 예외가 발생하더라도 연결과 명령이 모두 자동으로 닫힙니다. 단순화의 측면에서 그리고

는 :

  • 당신은 텍스트와 연결 걸리는 SqlCommand 생성자를 사용할 수 있습니다 - 유형 기본값을 Text에 어쨌든.
  • 적어도 사소한 프로젝트의 경우 스토리지 코드와 UI 코드를 개인적으로 분리하려고합니다. ASP.NET MVC를 사용하기 위해 변경하지 않더라도 적어도 분리에 대한 아이디어를 얻으려면 ASP.NET MVC를 살펴 봐야합니다.
3

Button2_Click(object sender, EventArgs e) 메서드에서 SQL Injection을 피하기 위해 매개 변수화 된 쿼리를 사용해야합니다. 이것이 표준 방법입니다.

protected void Button2_Click(object sender, EventArgs e) 
{ 
    string connectionString = ConfigurationManager.ConnectionStrings["sqlstudentConnectionString"].ConnectionString; 
    string command = @"INSERT INTO [student] (
     studentID, studentFirstName, studentLastName 
    ) VALUES (
     @studID, @FName, @LName 
    )"; 

    using (SqlConnection sqlConnection = new SqlConnection(connectionString)) 
    using (SqlCommand cmd = new SqlCommand()) 
    { 
     cmd.CommandType = System.Data.CommandType.Text; 
     cmd.CommandText = command; 
     cmd.Parameters.AddWithValue("@studID", TextID.Text); 
     cmd.Parameters.AddWithValue("@FName", TextFirstName.Text); 
     cmd.Parameters.AddWithValue("@LName", TextLastName.Text); 
     cmd.Connection = sqlConnection; 

     sqlConnection.Open(); 
     cmd.ExecuteNonQuery(); 
     sqlConnection.Close(); 
    } 

    TextID.Text = ""; 
    TextFirstName.Text = ""; 
    TextLastName.Text = ""; 
    populateDataGrid(); 
} 

호프가 도움이 되길 바랍니다.