【问题标题】:webform multi column single row SQL Server result to vb variableswebform多列单行SQL Server结果到vb变量
【发布时间】:2013-08-26 17:13:56
【问题描述】:

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

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

感谢任何示例和指示。

【问题讨论】:

    标签: asp.net sql sql-server vb.net webforms


    【解决方案1】:

    试试这个:

        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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2012-08-05
      • 2013-09-10
      • 1970-01-01
      相关资源
      最近更新 更多