VB.Net SQL插入难度

时间:2012-07-29 11:35:30

标签: vb.net

我在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

1 个答案:

答案 0 :(得分: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