使用 VB.NET 在 Windows 应用程序中连接 MySQL
如何在 VB.NET 应用程序中使用 MySQL 作为数据库。
引言
如今,许多人尝试使用 MySQL 作为数据库,因为 MySQL 是一种开源关系数据库管理系统,主要广泛用于 Web 应用程序。在这里,我们将以 Windows 应用程序为例,介绍 MySQL 连接。
Using the Code
在建立任何连接之前,我们需要从 MySQL 官方网站下载最新版本的 MySQL Connector:https://dev.mysqlserver.cn/downloads/connector/,下载 DLL 文件后。
步骤 1
现在,我们需要将 DLL 文件作为引用添加到我们的项目中。为此,右键单击项目,选择“添加引用”,然后选择“浏览”按钮,并从保存 DLL 文件的目录中选择 DLL 文件。此连接字符串已放置在 App.config 文件中。然后在连接字符串中,将 DataSource
设置为如下:
add name="Demo" connectionString="server=localhost;database=demo;uid=root;password=;" providerName="MySql.Data.MySqlClient"
第二步
现在,我们需要导入 Imports
文件以用于 MySQL 客户端,如下所示:
Imports MySql.Data Imports MySql.Data.MySqlClient
这里,我将使用 Login
作为示例,以建立数据库和应用程序之间的连接,请参阅以下代码:
Public Class Login 'MySQL Public conn As SqlConnection Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Try Dim a, b As String a = TextBox1.Text b = TextBox2.Text Dim flag As Integer = 0 conn = New MySqlConnection(ConfigurationManager.ConnectionStrings("Demo").ConnectionString) conn.Open() '' MySQL Commands Dim mySelectQuery As String = "select * from demo.login where username='" & TextBox1.Text & "' and u_password='" & TextBox2.Text & "' " Dim myCommand As New MySqlCommand(mySelectQuery, conn) Dim rd As MySqlDataReader rd = myCommand.ExecuteReader() '' Data Reading While (rd.Read()) If (a = rd(0).ToString.Trim() And b = rd(1).ToString.Trim()) Then flag = 1 Exit While Else flag = 0 End If End While If (flag = 1) Then MsgBox("Login Sucessfully", MsgBoxStyle.OkOnly, "Done") Me.Hide() MDI.Show() Else MsgBox("Username or Password is Wrong....", MsgBoxStyle.Critical, "Error") End If '' Closing Database. conn.Close() Catch ex As Exception MsgBox("Error Loading Database", MsgBoxStyle.Critical, "Error") End Try End Sub
对于 Insert
和 Update
,如下所示:
''UPDATE: Try conn = New MySqlConnection(ConfigurationManager.ConnectionStrings("Demo").ConnectionString) conn.Open() Dim query as String query = "update demo.login set <set as="" follows="" query=""> conn.Close() Catch ex as Exception MsgBox("Some message as example shown above") End Try '' INSERT Try Dim rd As SqlDataReader conn = New MySqlConnection(ConfigurationManager.ConnectionStrings("Demo").ConnectionString) conn.Open() Dim query as String query = "insert into demo.login values <insert> Dim Command As New MySqlCommand(query, con) Dim rd As MySqlDataReader rd = Command.ExecuteReader() MsgBox("Data saved Successfully", MsgBoxStyle.MsgBoxRight, "Done") conn.Close() Catch ex as Exception MsgBox("Some message goes here") End Try
本主题帮助您使用 Select
、Update
和 Insert
查询创建与 MySql 数据库的连接。