2012-05-07 49 views
-1

如何在Visual Studio 2005中以窗口形式将数据添加到sql数据库?从VB.NET保存到数据库WinForms

我在保存时遇到问题。

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 
+6

您有SQL注入漏洞。 – SLaks

+1

你的实际问题是什么?在标题中的关键字混乱之间,我无法在此处看到任何问题。 –

+3

这不仅仅是一个小小的漏洞:它通过**类型的脆弱性造成了巨大的,巨大的,驱动工业推土机,进一步加剧了这一事实,即您将连接的主要罪行称为sa。 –

回答

5

嗯,乍一看,我可以在你的查询文本看到一个缺失值:
我可以指望9场,只有8个值......但是这可能只是一个打字错误。

更严重的是缺少参数的使用。正如@slaks在评论中指出的那样,这种代码导致Sql Injection Attacks。此外,您将所有值作为字符串传递。我怀疑你的[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