2012-10-18 3 views
0

데이터베이스에 gridview 데이터를 전달하려고합니다. 내가 겪고있는 문제는 내 gridview의 모든 데이터가 데이터베이스에 들어오는 것이 아니라는 것입니다. 메시지 박스를하는 것은 단지 이름의 열이있는 것입니다 보여줍니다. 여기에 주로 SQL 주입을 방지하기 위해 SQL 명령 만 사용하는 매개 변수를 만들 문자열을 연결하지 마십시오 내 코드SQL 명령이 db에 DataGrid의 모든 값을 삽입하지 않습니다.

Protected Sub Button2_Click1(sender As Object, e As EventArgs) Handles Button2.Click 
    Dim sc As StringCollection = New StringCollection 
    Dim field1 As String = String.Empty 
    Dim i As Integer = 0 
    Do While (i < GridView1.Rows.Count) 
     field1 = GridView1.Rows(i).Cells(0).Text 
     i = (i + 1) 
    Loop 
    ' get the field to be Inserted 
    sc.Add(field1) 
    ' add the field to be Inserted in the StringCollection 
    InsertRecords(sc) 
    ' call method for insert and pass the StringCollection values 

End Sub 





Dim conn As MySqlConnection = New MySqlConnection("Server=****************;Database=******;Uid=*******;Pwd=****;allow user variables=true") 
    Dim sb As StringBuilder = New StringBuilder(String.Empty) 
    For Each item As String In sc 
     Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (" 
     sb.AppendFormat("{0}'{1}' ", sqlStatement, item) 

    Next 
    sb.Append(")") 

    MsgBox(sb.ToString) 

    Try 
     conn.Open() 
     Dim cmd As MySqlCommand = New MySqlCommand(sb.ToString, conn) 
     cmd.CommandType = CommandType.Text 
     cmd.ExecuteNonQuery() 

    Catch ex As System.Data.SqlClient.SqlException 
     Dim msg As String = "Insert Error:" 
     msg = (msg + ex.Message) 
     Throw New Exception(msg) 
    Finally 
     conn.Close() 
    End Try 
End Sub 
+0

문자열을 연결하여 sql 명령을 만들지는 않지만 매개 변수를 사용하지 마십시오. –

+0

예를 보여 주시겠습니까 – user1712552

+0

'sc' 란 무엇이며 명령을 실행하는 코드는 어디에 있습니까? –

답변

1

입니다. 내가 필요한 모든 특성을 가진 사용자 정의 클래스의 컬렉션처럼 sc을 사용했습니다

Const sqlStatement As String = "INSERT INTO student(name, age, adress) VALUES (?Pname,?Page,?Padress)" 
Try 
    Using con = New MySqlConnection(connectionString) 
     con.Open() 
     For Each item In sc 
      Using cmd = New MySqlCommand(sqlStatement, con) 
       cmd.Parameters.AddWithValue("?Pname", item.Name) 
       cmd.Parameters.AddWithValue("?Page", item.Page) 
       cmd.Parameters.AddWithValue("?Padress", item.Padress) 
       cmd.ExecuteNonQuery() 
      End Using 
     Next 
    End Using 
Catch ex As System.Data.SqlClient.SqlException 
    ' log message ' 
    Throw ' don't use throw new Exception or throw ex ' 
End Try 

참고. 그러나 그것이 정확하지 않더라도, 그것이 어떻게 작동하는지 당신에게 아이디어를 줄 것입니다.

+0

+1 그리고 INSERT 문은 완전히 잘못되었습니다. – Steve

+0

@ 스티브 : 그리고 내 SQL 문을 추가하는 것을 잊었습니다.) –

+0

감사합니다. 정말 감사 하네 !! – user1712552

관련 문제