-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 に答える