2016-03-01 94 views
0

當我嘗試將數據插入到數據庫時,我的代碼出現問題,它檢查匹配的用戶名的部分不斷彈出錯誤以選擇其他用戶名。我不知道我做錯了什麼,任何幫助將不勝感激。我似乎無法將數據插入到我的數據庫中

這是我的代碼:

'Connecting to SQL Database and executing Query 
Dim Strconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\phermacy.mdf;Integrated Security=True;User Instance=True" 

Dim Strcmd As String = "INSERT INTO tblstaff_info(id,fname,lname,sex,nationality,status,dob,age,nationality,state,address,phone,email,dateemp,username,password) VALUES ('" & txtregid.Text & "','" & txtfname.Text & "','" & txtlname.Text & "','" & cmbstaffsex.Text & "','" & cmbstatus.Text & "','" & dtpickerdob.Text & "','" & txtage.Text & "','" & txtnationality.Text & "','" & txtstateofo.Text & "','" & rtbaddress.Text & "','" & txtphone.Text & "','" & txtemail.Text & "','" & dtpdateemp.Text & "','" & txtusername.Text & "','" & txtpassword.Text & "');" 

Dim da As New SqlDataAdapter 
Dim ds As New DataSet 
Dim sqlcmd As SqlCommand 
sqlconn = New SqlConnection(Strconn) 

Try 
     sqlconn.Open() 
Catch ex As Exception 
     MsgBox("Could not connect to DataBase. Application will close now!", vbCritical, "Database Error") 
     End 
End Try 

sqlcmd = New SqlCommand(Strcmd, sqlconn) 
da.SelectCommand = sqlcmd 

sqlcmd.Dispose() 
sqlconn.Close() 

'Exception Handling----------------------- 
Dim exc As Exception = Nothing 

Try 
     da.Fill(ds) 
Catch ex As Exception 
     exc = ex 
Finally 
     If Not (exc) Is Nothing Then 
      MsgBox("User Name Already Exist. Please select a different User Name!", vbExclamation, "Already Exist") 
      txtusername.Focus() 
     Else 
      MsgBox("Save info Successful.", vbInformation, "Successful") 
      'Me.Close() 
      'loginform.Show() 
     End If 
End Try 
+2

你聽說過sql注入嗎? –

+0

有人說小鮑比表? –

+0

是的,我有伊萬Starostin你最好有什麼建議嗎? –

回答

0

整個用戶實例和AttachDbFileName =方法是有缺陷的 - 在最好的!在Visual Studio中運行應用程序時,它將複製.mdf文件(從您的App_Data目錄到輸出目錄 - 通常爲.\bin\debug) - 最有可能爲,您的INSERT工作得很好 - 但是您只是看着錯誤.mdf文件到底!

如果你想堅持使用這種方法,然後嘗試把一個斷點連接的.Close()電話 - 然後檢查.mdf文件與SQL Server管理Studio Express的 - 我幾乎可以肯定你的數據是存在的。

在我看來真正的解決方案

  1. 安裝SQL Server Express(和你已經做到這一點無論如何)

  2. 安裝SQL Server Management Studio中快速

  3. 中創建您的數據庫SSMS Express,給它一個邏輯名稱(例如Pharmacy - che !CK拼寫)

  4. 連接使用其邏輯數據庫名稱(當你在服務器上創建它給出)它 - 和周圍不亂用物理數據庫文件和用戶實例。在這種情況下,您的連接字符串將是這樣的:

    Data Source=.\\SQLEXPRESS;Database=Pharmacy;Integrated Security=True 
    

    和其他一切是正是和以前一樣......

另見阿龍貝特朗的優秀博客文章Bad habits to kick: using AttachDbFileName更多背景信息。

相關問題