从VB.NET WinForms保存到数据库

Shr*_*ray -1 vb.net sql-server .net-4.0 winforms

如何在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
Run Code Online (Sandbox Code Playgroud)

Ste*_*eve 5

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

更严重的是缺乏参数使用.正如@slaks在其评论中指出的那样,这种代码会导致Sql注入攻击.此外,您将所有值作为字符串传递.我怀疑你的[staff]表只包含文本字段(DOB,DateJoinIn,AppointedAs).如果是这样,您的架构设计就会被严重破坏.参数也可以帮助避免这种错误.最后,与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 
Run Code Online (Sandbox Code Playgroud)