0

我今天在这里浏览了几个问题,并认为我在兜圈子。

我的网络表单有许多元素,包括username下拉列表(由 SQL 语句填充)

在提交表单时,我希望aspx.vb文件后面的代码运行一个select top 1查询并返回一行包含 4 列的数据。

返回的 SQL 查询结果 4 列将稍后在 aspx.vb 文件中使用,因此我想将每一列分配给一个变量。我正在努力完成这项任务并将查询的列结果分配给变量。

Protected Sub submitbtn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles submitbtn.Click


    Dim connString1 As String = System.Configuration.ConfigurationManager.ConnectionStrings("ConnectionString").ToString
    Dim conn As New SqlConnection(connString1)
    Dim sql1 As String = ""

    Dim col1h As String = ""
    Dim col2r As String = ""
    Dim col3title As String = ""
    Dim col4UQN As String = ""

    sql1 = "SELECT TOP 1 col1h,col2r,col3title, col4UNQ  from tblDistinctUserOHR where colID_Username= '" + username + "' "

    Dim cmd1 As New SqlCommand(sql1, conn)
'open the connection
'run the sql
'the result will always be found but in case its not some form of safety catch (the variables stay as empty strings 
'assign the results to the variables
'close connections
'lots of other code 
    End Sub

有人可以指出我正确的方向来运行 SQL 并将结果分配给变量。我一直在阅读ExecuteScalar()SqlDataReader但这似乎不是正确的选择,因为我发现的唯一示例处理单个结果或具有单列的大量行

感谢您提供任何示例和指示。

4

1 回答 1

0

尝试这个:

    Dim da As New OleDb.OleDbDataAdapter(sql1, conn)
    Dim dt As New DataTable
    da.Fill(dt)

    If dt.Rows.Count < 0 Then
        col1h = dt.Rows(0).Item("col1h")
        col2r = dt.Rows(0).Item("col2r")
        col3title = dt.Rows(0).Item("col3title")
        col4UQN = dt.Rows(0).Item("col4UQN")
    Else
        'No rows found
    End If
于 2013-08-26T17:22:17.357 回答