简单的VB语法,用于显示数据库中的某些值

时间:2011-05-24 13:24:29

标签: mysql vb.net visual-studio

我是Visual Basic的新手(使用visual studio 2010)。我只是做一些连接到mysql数据库的测试。

一旦我进行了sql查询,我不知道如何调用这些值。

如何解决此问题,即在表单上的标签上显示值?

代码:

Imports MySql.Data.MySqlClient
Public Class Form1

    Dim ServerString As String = "Server = localhost; User Id = root; database = CALIBRA"
    Dim SQLConnection As MySqlConnection = New MySqlConnection

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

        SQLConnection.ConnectionString = ServerString

        Try
            If SQLConnection.State = ConnectionState.Closed Then
                SQLConnection.Open()
                MsgBox("Successfully connected to MySQL database.")
            Else
                SQLConnection.Close()
                MsgBox("Connection is closed.")
            End If
        Catch ex As Exception
            MsgBox(ex.ToString)
        End Try
    End Sub

    Public Sub calibra_query(ByRef SQLStatement As String)
        Dim cmd As MySqlCommand = New MySqlCommand

        With cmd
            .CommandText = SQLStatement
            .CommandType = CommandType.Text
            .Connection = SQLConnection
            .ExecuteNonQuery()
        End With

        SQLConnection.Close()
        MsgBox("Records Successfully Retrieved")
        SQLConnection.Dispose()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim SQLStatement As String = "SELECT Auto1, Auto2, TotalWeight FROM txticket WHERE TicketCode = '12210'"
        calibra_query(SQLStatement)

        Dim Automobile1, Automobile2, TotalWgt As Long

    SOMETHING MISSING HERE
    SOMETHING MISSING HERE

    Label2.Text = Automobile1.ToString()
    Label2.Text = Automobile2.ToString()
    Label2.Text = TotalWgt.ToString()

    End Sub
End Class

我在“在这里丢失的东西”中加入了什么?非常感谢。

1 个答案:

答案 0 :(得分:5)

您需要一个数据读取器才能读取从sql查询返回的内容。你的Sub calibra_query正在执行一个非阅读器,它不会做你需要的。您只想将executeNonReader用于不需要结果的事物。 (例如,像更新声明)

你想要更像这样的东西:

 Dim cmd As MySqlCommand = New MySqlCommand

With cmd
    .CommandText = SQLStatement
    .CommandType = CommandType.Text
    .Connection = SQLConnection
End With

  Dim myReader as MySqlDataReader = myCommand.ExecuteReader

  If myReader.Read Then
     TextBox1.Text = myReader.GetString(0)
     TextBox2.Text = myReader.Getstring(1)
     TextBox3.Text = myReader.GetInt32(2)
  End If

  myReader.Close()
  SQLConnection.Close()
  MsgBox("Records Successfully Retrieved")
  SQLConnection.Dispose()

我在您的查询中假设3个字段的类型,并将其输出到文本框以提供您的想法。这也假设你只会得到一条记录。

(编辑:修复格式化)