gpt4 book ai didi

mysql - 简单的 VB 语法来显示数据库中的一些值

转载 作者:太空宇宙 更新时间:2023-11-03 10:25:33 25 4
gpt4 key购买 nike

我是 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

我应该在“这里缺少什么”中输入什么?非常感谢。

最佳答案

您将需要一个数据读取器来读取从 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 个字段的类型,并将其输出到文本框以提供您的想法。这还假设您只会因此获得一条记录。

(编辑:修复格式)

关于mysql - 简单的 VB 语法来显示数据库中的一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6111114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com