-1

我在 vs 2010 中编程一个 vb.net 项目。不知道我插入数据时发生了什么,因为它给出了以下消息:

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
4

1 回答 1

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

于 2012-07-29T11:47:59.567 回答