0

我正在尝试将 gridview 数据传递到数据库中。我遇到的问题是,并非我的gridview 中的所有数据都进入了数据库。做一个消息框只显示名称列。这是我的代码

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
4

1 回答 1

1

不要连接字符串来创建 sql 命令,而是使用参数主要避免 sql 注入。

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

请注意,我已经使用sc了具有所有需要属性的自定义类的集合。但即使这不正确,它也应该让您了解它是如何工作的。

于 2012-10-18T11:34:07.113 回答