2012-07-29 50 views
-1

我在vs 2010中编写了一个vb.net项目。 不知道发生了什么事,当我插入的数据,因为它给出了这样的消息:VB.Net SQL插入难度

A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

有什么不对?

这里,使得它

Imports System.Data 
Imports System.Data.SqlClient 


Public Class atl 

Dim myconnection As SqlConnection 


    Dim mycommand As SqlCommand 


Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True" 



Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click 
    myconnection = New SqlConnection(myConnectionString) 
    mycommand = New SqlCommand("insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) values ('" & txtNome.Text & "','" & txtMorada.Text & _ 
           "','" & ComboSexo.Text & "','" & CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd") & "','" & txtTelemovel.Text & "','" & ComboBox1.Text & "')", myconnection) 
    myconnection.Open() 
    Try 
     mycommand.ExecuteNonQuery() 
     Label1.Content = "O atleta " + txtNome.Text + " foi registado!!!" 
    Catch ex As Exception 
     Label1.Content = "Falhou a ligação a base de dados!!!" 
    End Try 
End Sub 

回答

1

做一些你的价值观包含单引号的代码的一部分吗?您的声明易受到sql injecton的影响。为什么你不使用SQL参数?

Dim myConnectionString As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\uss.mdf;Integrated Security=True;User Instance=True" 
Dim sqlStatement = "insert into atl([nome],[morada],[sexo],[datan],[telf],[desporto]) " 
sqlStatement &= "VALUES (@nome, @morada, @sexo, @datan, @telf, @desporto)" 

Using xConn As New SqlConnection(myConnectionString) 
    Try 
     Dim xComm As New SqlCommand(sqlStatement, xConn) 
     With xComm 
      .CommandType = CommandType.Text 
      .Parameters.AddWithValue("@nome", txtNome.Text) 
      .Parameters.AddWithValue("@morada", txtMorada.Text) 
      .Parameters.AddWithValue("@sexo", ComboSexo.Text) 
      .Parameters.AddWithValue("@datan", CType(txtDataN.Text, DateTime).ToString("yyyy-MM-dd")) 
      .Parameters.AddWithValue("@telf", txtTelemovel.Text) 
      .Parameters.AddWithValue("@desporto", ComboBox1.Text) 
     End With 

     xConn.Open() 
     xComm.ExecuteNonQuery() 
     xComm.Dispose() 
    Catch ex As SqlException 
     MsgBox (ex.Message) 
    End Try 
End Using 

还你有一个错误的位置:CType(txtDataN.Text, DateTime).ToString("yyy-MM-dd")它应该yyyy-MM-dd没有yyy-MM-dd

+0

星爷将ty它的工作原理,但...我有一个奇怪的东西hapening到我插入数据...它disapeares“LITRALLY “不知道为什么......我只是注册它,然后当我停止dibugger并等待片刻,再次打开调试项目de记录不存在,如果我打开数据库没有记录,只是默认一,没有别的,为什么? – 2012-07-29 12:49:58