将从mysql查询获取的值显示到VB.net文本框

时间:2016-12-15 10:04:14

标签: mysql vb.net count textbox

我试图在vb.net的文本框中显示我从COUNT(*)查询中获取的值,但不显示获得的值,而是显示实际查询。

这是我的代码:

Imports MySql.Data.MySqlClient
Public Class Statistics
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim query As String
Dim dadapter As New MySqlDataAdapter

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    conn = New MySqlConnection
    conn.ConnectionString =
        "server=localhost;userid=root;database=librarydatabase"
    Dim reader As MySqlDataReader


    Try
        conn.Open()
        query = "SELECT COUNT(*) FROM login where users='" & Username.Text & "'"


        command = New MySqlCommand(query, conn)
        reader = command.ExecuteReader

        dadapter.SelectCommand = command
        If reader.HasRows Then
            reader.Read()
            takenout.Text = (query)


        End If

        conn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()

    End Try

End Sub

以下是我的计划的屏幕截图:link

在尝试修复代码时,我将其更改为使用takenout.Text =(reader.read())替换takenout.Text =(查询)并删除上面的reader.read())和dadapter.SelectCommand = command < / p>

以下是更改后的代码:

Imports MySql.Data.MySqlClient

Public Class Statistics
Dim conn As MySqlConnection
Dim command As MySqlCommand
Dim query As String
Dim dadapter As New MySqlDataAdapter

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    conn = New MySqlConnection
    conn.ConnectionString =
        "server=localhost;userid=root;database=librarydatabase"
    Dim reader As MySqlDataReader

    Try
        conn.Open()
        query = "SELECT COUNT(*) FROM login where users='" & Username.Text & "'"


        command = New MySqlCommand(query, conn)
        reader = command.ExecuteReader


        If reader.HasRows() Then

            takenout.Text = (reader.Read())


        End If

        conn.Close()
    Catch ex As MySqlException
        MessageBox.Show(ex.Message)
    Finally
        conn.Dispose()

    End Try

End Sub

此代码无法解决问题,但无论用户名文本框中有什么内容,按下按钮时文本框中都显示为true。

以下是link

的图片

2 个答案:

答案 0 :(得分:1)

改为使用command.ExecuteScalar()

答案 1 :(得分:0)

使用command.executescalar()修复了这个问题。

以下是固定代码的副本,如果其他人有类似的问题,并希望看到一个有效的例子。

long double