2017-03-11 59 views
0

我有TableAdapter名稱ballotsTableAdapter,我想用它查詢我的數據庫表選票而不將它作爲查詢添加到表中,如果有意義的話。使用tableadapter如何在頁面後面的代碼中查詢我的db表

Dim adapter As New eVoteTableAdapters.ballotsTableAdapter 
Dim ballot_IDIn As Integer = ballot_ID 
Dim name As String 
Dim sd As Date 
Dim ed As Date 
name = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT name FROM ballots WHERE ballod_ID = @ballot_IDIn), String) 
sd = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT startDate FROM ballots WHERE ballod_ID = @ballot_IDIn), Date) 
ed = CType(adapter.Adapter.SelectCommand.ExecuteScalar(SELECT endDate FROM ballots WHERE ballod_ID = @ballot_IDIn), Date) 

對不起,我很確定這是一個業餘愛好者的問題。

+0

用'''圍住你的查詢使它成爲一個字符串 - 'SELECT name FROM ballots WHERE ballod_ID = @ ballot_IDIn'變成'$「SELECT name FROM ballots WHERE ballod_ID = {ballot_IDIn}」' - 對於初學者 –

+0

我只是這樣做,並得到錯誤:對象引用未設置爲對象的實例。 – JayyCodez

+1

@AlexM。,請不要建議使用字符串連接來創建SQL查詢,即使對於初學者。 – Fabio

回答

0

您需要提供查詢作爲一個字符串,併爲您的查詢提供

Public Function GetName(ballotId As Interger) As String 
    Dim query As String = "SELECT name FROM ballots WHERE ballod_ID = @ballot_IDIn" 
    Using connection = New SqlConnection("connection string") 
     Using command = New SqlCommand(query, connection) 
      Dim parameter = New SqlParameter With 
      { 
       .ParameterName = "ballot_IDIn", 
       .SqlDbType = SqlDbType.Int, 
       .Value = ballotId 
      } 
      command.Parameters.Add(parameter) 
      connection.Open() 
      Dim result = commnad.ExecuteScalar() 
      Return result.ToString() 
     End Using 
    End Using 
End Function 

我建議使用單獨的SqlCommand SQL參數沒有的TableAdapter,甚至每個查詢創建SqlConnection新實例。

+0

這很好。 – JayyCodez

相關問題