2016-03-01 113 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更多背景信息。

相关问题