将webform多列单行SQL Server结果转换为vb变量



我今天看了这里的几个问题,觉得我在兜圈子。

我的网络表单有很多元素,包括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的文章,但这似乎不是正确的选择,因为我发现的唯一例子是用单列处理单个结果或多行

谢谢你的样品和指点。

试试这个:

    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

最新更新