2012-05-07 45 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