SqlClient命令错误:“列名'A'无效”

时间:2010-12-07 06:59:59

标签: asp.net vb.net

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
    Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True")
    Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT * FROM a1_bustype where bustype=" & DropDownList1.SelectedItem.Text.ToString, SQLData)
    SQLData.Open()
    Dim dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
    If dtrReader.HasRows Then
        While dtrReader.Read()
            TextBox1.Text = dtrReader("buscode")
        End While
    End If

    dtrReader.Close()
    SQLData.Close()
End Sub

我在数据库tabel中有以下条目...在bustype列中我有..A / c seater volvo和总线代码是S41

当我运行网页时,它显示以下错误无效的列名'A'

2 个答案:

答案 0 :(得分:1)

如果bustype是text或varchar,则必须在查询中添加单引号

UPD:我不确定它是如何进入vb的,就像这样:

"SELECT * FROM a1_bustype where bustype='" & DropDownList1.SelectedItem.Text.ToString & "'"

答案 1 :(得分:0)

正如X2在他的回答中所说,你需要用单引号括起你的字符串,所以将开始Dim cmdSelect...的行改为:

Dim cmdSelect As New System.Data.SqlClient.SqlCommand(String.Format("SELECT * FROM a1_bustype where bustype='{0}'", DropDownList1.SelectedItem.Text.Replace("'", "''")), SQLData)

如果DropDownList中的值本身可以包含单引号,这也会使它支持。

但是,如果出现错误,您不会在代码中正确关闭内容,我建议将其更改为:

Protected Sub DropDownList1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
    Using SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True")
        Using cmdSelect As New System.Data.SqlClient.SqlCommand(String.Format("SELECT * FROM a1_bustype where bustype='{0}'", DropDownList1.SelectedItem.Text.Replace("'", "''")), SQLData)
            SQLData.Open()
            Using dtrReader As System.Data.SqlClient.SqlDataReader = cmdSelect.ExecuteReader()
                If dtrReader.HasRows Then
                    While dtrReader.Read()
                        TextBox1.Text = dtrReader("buscode")
                    End While
                End If
            End Using
        End Using
    End Using
End Sub

即使在某处出现异常,Using / End Using语句也会确保资源得到正确处理。