如何使用VB.NET在mysql中选择所有列值

时间:2018-11-25 11:20:11

标签: mysql vb.net

我的表有两列:“总计”和“返回”,我试图从这两列中获取所有列的值,但不适用于我。它只需要列中的第一行,我想要列中的总值

我的代码:

 Private Sub TotalTextBox_TextChanged(sender As Object, e As EventArgs) Handles TotalTextBox.TextChanged
    Dim str As String = "Server=localhost;Port=3306;Database=testdb;Uid=root;Pwd=password"

    Using net As New MySqlConnection(str)

        Dim totalnet As String = "Select * from testata where Qty_Returned and Total" 

        Dim cm As New MySqlCommand(totalnet, net)

        net.Open()
        Dim rdnet As MySqlDataReader = cm.ExecuteReader()

        If rdnet.Read() Then
            Label16.Text = rdnet.GetString(12) - rdnet.GetString(11)
        Else

        End If
    End Using

End Sub

2 个答案:

答案 0 :(得分:0)

很高兴您能正常使用。只是一些建议... 为此以及所有代码启用Option Strict。 评论是内联的。

Private Sub testdataDataGridView_DataBindingComplete(sender As Object, e As DataGridViewBindingCompleteEventArgs) Handles testataDataGridView.DataBindingComplete
        'A Using...End Using block will ensure that your objects that use unmanages 
        'resources are closed and disposed event if there is an error in the code
        Using con As New MySqlConnection("Server=localhost;Port=3306;Database=testdb;   Uid=root;Pwd=1234")
            'A command object constructor can take an query string and connection as arguments
            Using cmd As New MySqlCommand("select sum(Qty_Returned) FROM testdata", con)
                'Open the connection at the last possible minute
                con.Open()
                Dim sqlresult = cmd.ExecuteScalar
                Label16.Text = sqlresult.ToString
            End Using
            Using cmg As New MySqlCommand("select sum(Total) FROM testgdata", con)
                Dim sqlresult2 = cmg.ExecuteScalar
                Label10.Text = sqlresult2.ToString
            End Using
        End Using
        Label18.Text = (CInt(La
End Sub

不确定在此事件中为何使用此代码。

答案 1 :(得分:-1)

我用以下代码得到了解决方案:

 Private Sub testdataDataGridView_DataBindingComplete(sender As Object, e As     DataGridViewBindingCompleteEventArgs) Handles testataDataGridView.DataBindingComplete
    Dim con As New MySqlConnection("Server=localhost;Port=3306;Database=testdb;   Uid=root;Pwd=1234")

    Dim cmd As New MySqlCommand
    Dim cmg As New MySqlCommand

    con.Open()
    cmd.Connection = con
    cmd.CommandText = "select sum(Qty_Returned) FROM testdata"
    Dim sqlresult As Object
    sqlresult = cmd.ExecuteScalar
    Dim str1 As String
    str1 = sqlresult
    Label16.Text = str1
    cmg.Connection = con
    cmg.CommandText = "select sum(Total) FROM testgdata"
    Dim sqlresult2 As Object
    sqlresult2 = cmg.ExecuteScalar
    Dim str2 As String
    str2 = sqlresult2
    Label10.Text = str2

    Label18.Text = Label10.Text - Label16.Text
End Sub