MySQL 查询(求和)在 VB 中不起作用

MySQL query (sum) not working in VB

我想在 MySQL 数据库列中添加所有员工的年龄(使用求和查询),然后在 [=20= 中单击按钮显示其结果(值) ] 在 textbox.I 中尝试过,但它不是 working.I 我无法理解这个 out.Please 帮助....Image

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click

Dim Mysqlconn As New MySqlConnection

Mysqlconn.ConnectionString = "server=localhost;userid=root;port=85;password=andy1234;database=data"



Try
    Mysqlconn.Open()
    command.Connection = Mysqlconn

    command.CommandText = "select sum(age) from data.etable"

    Dim sqlresult As Object
    sqlresult = command.ExecuteScalar

    Dim str As String
    str = sqlresult
    TextBox5.Text = str

    Mysqlconn.Close()

Catch ex As MySqlException
    MessageBox.Show(ex.Message)
    Mysqlconn.Dispose()

End Try
End Sub

Mysql

标准端口 3306 上的演示

架构

create table etable
(   eid int auto_increment primary key,
    age int not null
);

insert etable(age) values (1),(2),(3);

VB代码

Imports MySql.Data.MySqlClient


Public Class Form1
    Dim conn As New MySqlConnection

    Public Sub connect()
        ' Perform a connection test, and save ConnectionString
        ' in Module-level variable "conn"

        Dim dbname As String = "dbname"
        Dim hostname As String = "hostname"
        Dim user As String = "dbuser"
        Dim password As String = "password"
        If Not conn Is Nothing Then conn.Close()
        conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}", hostname, user, password, dbname)
        Try
            conn.Open()
            MsgBox("Connection Test Successful")
            ' and ConnectionString set for subsequent queries
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        conn.Close() ' close connection for now
    End Sub

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        connect()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim iAgeSum As Integer
        Try
            conn.Open()
        Catch ex As Exception
        End Try
        Dim cmd As New MySqlCommand(String.Format("select sum(age) as ageSum from etable"), conn)
        Dim result = cmd.ExecuteScalar()
        If result Is Nothing Then
            TextBox1.Text = "junk"
        Else
            iAgeSum = Convert.ToInt32(result.ToString()) ' for the purpose of showing conversion
            TextBox1.Text = iAgeSum
        End If

        conn.Close()
    End Sub
End Class

截图