-1

如何在 Visual Studio 2005 中将窗口形式的数据添加到 sql 数据库中?

我在保存时遇到问题。

Public Class Staff    
    Dim myconnection As SqlConnection
    Dim mycommand As SqlCommand
    Dim dr As SqlDataReader
    Dim dr1 As SqlDataReader
    Dim ra As Integer
    Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click
        myconnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=medisam")
        myconnection.Open()
        mycommand = New SqlCommand("insert into staff([FirstName],[LastName],[Address],[DOB], [TelephoneNum], [DateJoinIn], [HighestQualifi], [AppointedAs], [Salary]) VALUES ('" & txtfname.Text & "','" & txtlname.Text & "','" & txtaddress.Text & "','" & txtdob.Text & "','" & txttelephone.Text & "','" & txthqualifi.Text & "','" & ComboBox1.SelectedValue & "','" & txtsalary.Text & "')", myconnection)
        mycommand.ExecuteNonQuery()
        myconnection.Close()

    End Sub
End Class
4

1 回答 1

5

好吧,乍一看,我可以在您的查询文本中看到一个缺失值:
我可以计算 9 个字段并且只有 8 个值......但这可能只是一个打字错误。

更严重的是缺少参数使用。正如@slaks 在其评论中指出的那样,这种代码会导致Sql Injection Attacks。此外,您将所有值作为字符串传递。我怀疑您的[staff]表格是否只包含文本字段(DOB、DateJoinIn、ApointedAs)。如果是这样,您的架构设计就被严重破坏了。这些参数还可以帮助避免这种错误。最后,与 sa 帐户连接将导致您的 dba 追捕您并将您击败到离您生命只有一步之遥的地方。

请以这种方式重写您的方法:

Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click 
    Using (myconnection as SqlConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=medisam"))
        myconnection.Open() 
        mycommand = New SqlCommand("insert into staff([FirstName],[LastName],[Address],[DOB], " & _
                                   "[TelephoneNum], [DateJoinIn], [HighestQualifi], [AppointedAs], [Salary]) " & _
                                   "VALUES (@first, @last, @address, @dob, @tel, @dateJ, @highQ, @appointed, @sal)", myconnection)

        mycommand.Parameters.AddWithValue("@first", txtfname.Text)
        mycommand.Parameters.AddWithValue("@last", txtlname.Text) 
        mycommand.Parameters.AddWithValue("@address", txtaddress.Text)
        mycommand.Parameters.AddWithValue("@dob",txtdob.Text) ' if this is a date, need to convert
        mycommand.Parameters.AddWithValue("@tel",txttelephone.Text)
        mycommand.Parameters.AddWithValue("@dateJ", txt??? Missing ????)
        mycommand.Parameters.AddWithValue("@highQ",txthqualifi.Text)
        mycommand.Parameters.AddWithValue("@appointed",ComboBox1.SelectedValue) ' need to convert ??? 
        mycommand.Parameters.AddWithValue("@sal",txtsalary.Text) ' need to convert ???
        mycommand.ExecuteNonQuery() 
    End Using

End Sub 
于 2012-05-07T18:23:17.260 回答