VB计数文本框中的查询结果

时间:2013-01-27 23:26:09

标签: sql vb.net ms-access-2007

我想在文本框中的Access数据库上填充SQL计数查询的结果,显示有多少结果。例如,我有一个代码编号输入到数据库200次,我希望文本框显示200。

到目前为止我的代码:

    ID = DataGridView1.CurrentRow.Cells(0).Value
    fn = DataGridView1.CurrentRow.Cells(1).Value
    ln = DataGridView1.CurrentRow.Cells(2).Value
    SKU = DataGridView1.CurrentRow.Cells(4).Value
    FC = DataGridView1.CurrentRow.Cells(5).Value


    Dim countNoTwo As String = "SELECT COUNT skuNo FROM table WHERE skuNo = " & SKU & ""
    Dim connection As New OleDbConnection(duraGadgetDB)
    Dim dataadapter As New OleDbDataAdapter(countNoTwo, connection)
    Dim ds As New DataSet()
    connection.Open()
    dataadapter.Fill(ds, "dura")
    connection.Close()

   txtbox1.Text

如何将数据集的结果绑定到txtbox1.Text?

2 个答案:

答案 0 :(得分:1)

  • 首先,不要使用字符串连接来构建sql命令 (reason = Sql Injection +解析问题)
  • 其次,如果您的命令只返回一个您可以使用的结果 ExecuteScalar
  • 第三,使用Using statement确保您的连接和 命令在使用后正确处理

    Dim countNoTwo As String = "SELECT COUNT skuNo FROM table WHERE skuNo = ?"
    Using connection As New OleDbConnection(duraGadgetDB)
        Using command As New OleDbCommand(countNoTwo, connection)
           command.Parameters.AddWithValue("@sku", SKU)
           connection.Open()
           Dim result = Convert.ToInt32(command.ExecuteScalar())
           txtbox1.Text = result.ToString
        End Using
    End Using
    

答案 1 :(得分:0)

试试这个

Dim dt As DataTable = ds.Tables(0)
txtbox1.Text = dt.Rows(0).Item(0).ToString()