1

我有个问题。我在堆栈和其他网站上研究了这个问题,但没有找到答案。我想要一个插入命令,将字符串附加到现有列名。我有一张表,在不同的月份多次具有相同的列。列示例:name1为一月,name2为二月。address1代表 1 月,address2代表 2 月,以此类推。我遇到的唯一想法是如何将变量传递到列的数据中,我需要将变量添加到已经存在的列名中,这样我就不会有多个插入命令。这是我的代码。

 If MonthDDL.SelectedValue <> "" Then
        Select Case MonthDDL.SelectedValue  
            Case Is = "January"
                Month = "0"
                monthVar = "January"
            Case Is = "February"
                Month = "1"
                monthVar = "February"
            Case Is = "March"
                Month = "2"
                monthVar = "March"
            Case Is = "April"
                Month = "3"
                monthVar = "April"
            Case Is = "May"
                Month = "4"
                monthVar = "May"
            Case Is = "June"
                Month = "5"
                monthVar = "June"
            Case Is = "July"
                Month = "6"
                monthVar = "July"
            Case Is = "August"
                Month = "7"
                monthVar = "August"
            Case Is = "September"
                Month = "8"
                monthVar = "September"
            Case Is = "October"
                Month = "9"
                monthVar = "October"
            Case Is = "November"
                Month = "10"
                monthVar = "November"
            Case Is = "December"
                Month = "11"
                monthVar = "December"
                'Case Else
        End Select
        selDate = MonthDDL.SelectedValue
    Else
        lblSelect.Visible = True
    End If

DBCONN.Open()
        Dim SqlUpdate = New SqlCommand("SELECT * FROM table WHERE variable = '" + Session("sessionvariable") + "'", DBCONN)

MonthDDL.SelectedValue = monthVar And dr.HasRows = True Then
                SqlUpdateCommd = New SqlCommand("UPDATE table SET [table].[name] '"+ Month +'" = '" & contact & "',[table].[address]'"+ Month +'" = '" + address + "' WHERE variable = '" & Session("sessionvariable") & "'", DBCONN)
        ElseIf MonthDDL.SelectedValue = monthVar And dr.HasRows = False Then
            SqlUpdateCommd = New SqlCommand("INSERT INTO table (name '"+ Month +'", address '"+ Month +'", variable) Values ('" + contact + "', '" + address + "', Session("sessionvariable") + "')", DBCONN)

这可能吗?我是否接近以正确的方式解决这个问题。我为措辞道歉,我是 vb.net 的新手。我什至不确定要搜索什么,这可能就是我没有真正偶然发现答案的原因。先感谢您!

4

1 回答 1

2

德赖特是正确的。您真的不应该这样做,因为除其他外,如果变量是用户可定义的,它会使您的应用程序容易受到 SQL 注入攻击。重新设计数据库模式会更好,更简单,这样您就不会有这样的重复列。

但是,您的代码失败的可能原因是您在变量值之前和之后附加了撇号,例如:

"[table].[name '" & variable & "']"

请注意,上面的语句实际上会评估为如下内容:

"[table].[name '1']"

但是,你真正想要的可能是这样的:

"[table].[name1]"

因此,要做到这一点,您需要执行以下操作:

"[table].[name" & variable & "]"

然而,正如我所说,像这样构建动态 SQL 不仅是一个坏主意,而且还表明数据库模式设计不佳。

于 2013-01-04T20:25:23.017 回答