You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Windows10下VB.NET连接MySQL遇AuthenticationException异常求助

解决Windows10下VB.NET连接MySQL的SSPI认证异常

先修正代码中的基础错误

你代码里定义了连接对象cc,但Try块中调用的是conn.Open(),变量名不匹配,这会直接导致运行错误,先把这个问题修正。

针对SSPI认证异常的解决方案

1. 调整连接字符串的SSL配置

Win10默认的SSL/TLS策略与Win7不同,MySQL驱动可能尝试通过SSL连接本地数据库,但多数本地MySQL实例未配置SSL,因此需要显式指定SSL模式:
修改连接字符串,添加SslMode=none(禁用SSL):

Dim Str As String = "SERVER=localhost;uid=root;DATABASE=mag;PASSWORD=;SslMode=none;"

注意去掉参数名前后的空格(比如uid =root改成uid=root),避免连接字符串解析错误。

2. 正确设置TLS协议(VB.NET语法)

你之前用的是C#语法,VB.NET中需要按以下方式设置,且要放在创建连接对象之前:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls

这样同时兼容不同版本的TLS协议,避免因协议不匹配导致的认证失败。

3. 更新MySQL驱动版本

旧版MySql.Data.dll对Windows10的TLS支持存在缺陷,建议更新到最新稳定版:

  • 优先使用MySqlConnector(替代官方旧驱动的开源实现,兼容性更好)
  • 若坚持用官方驱动,升级到8.x版本

4. 捕获完整异常信息排查问题

原代码仅捕获MySqlException,但实际抛出的是AuthenticationException,修改捕获逻辑以获取内部错误详情:

Catch ex As Exception
    MessageBox.Show($"错误信息:{ex.Message}{vbCrLf}内部错误:{ex.InnerException?.Message}")
End Try

修正后的完整代码

Imports MySql.Data.MySqlClient
Public Class Form1

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        ' 设置TLS协议
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls
        
        ' 修正连接字符串,添加SSL模式配置,去掉多余空格
        Dim Str As String = "SERVER=localhost;uid=root;DATABASE=mag;PASSWORD=;SslMode=none;"
        Dim cc As New MySqlConnection(Str)
        
        Try
            cc.Open() ' 修正变量名错误
            ' 改用参数化查询,避免SQL注入风险
            Dim Sql = "SELECT * FROM tab1 WHERE login=@login and password=@password"
            Dim cmd = New MySqlCommand(Sql, cc)
            cmd.Parameters.AddWithValue("@login", TextBox1.Text)
            cmd.Parameters.AddWithValue("@password", TextBox2.Text)
            
            Dim dr = cmd.ExecuteReader()
            If dr.HasRows Then
                Me.Hide()
                Form2.Show()
            Else
                MsgBox("登录失败。", vbQuestion)
            End If
            dr.Close()
            cc.Close()
        Catch ex As Exception
            MessageBox.Show($"错误信息:{ex.Message}{vbCrLf}内部错误:{ex.InnerException?.Message}")
            ' 确保连接关闭
            If cc.State = ConnectionState.Open Then
                cc.Close()
            End If
        End Try
    End Sub
End Class

额外提醒:原代码存在严重的SQL注入风险,已改为参数化查询,务必使用这种方式避免安全问题。

内容的提问来源于stack exchange,提问作者Faika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 18:37:13