2013-08-26 46 views
0

我今天在這裏看了幾個問題,並認爲我會圍繞着圈子。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,但這似乎並不是正確的選擇,因爲我發現的唯一例子處理單個結果或單列的很多行

感謝您的任何示例和指針。

回答

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