使用 table 适配器如何在代码隐藏页面中查询我的数据库 table

Using a tableadapter how do I query my db table in the code behind page

我有一个名为 ballotsTableAdapter 的 TableAdapter,我想用它来查询我的数据库 table 选票,而不是将它作为查询添加到 table,如果这样的话。

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)

提前抱歉,我确定这是一个业余问题。

您需要以字符串形式提供查询并为您的查询提供 sql 个参数

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

我建议使用不带 TableAdapter 的单独 SqlCommand,甚至为每个查询创建 SqlConnection 的新实例。