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

MySQL数据库连接失败求助:配置正确仍无法建立连接

MySQL Connection Failure in VB.NET Login System

Hey there, let's break down why your database connection isn't sticking even when you expect it to work. Here are targeted checks and fixes to resolve this:

1. Fix the Connection String Format

Your current connection string has unnecessary single quotes around every parameter—MySQL doesn't recognize these, and this is almost certainly causing a parsing failure. Rewrite it like this:

conn.ConnectionString = $"Server={ServerMySQL};Port={PortMySQL};Database={DBNameMySQL};Uid={UserNameMySQL};Pwd={PwdMySQL};"

If you're using an older VB.NET version that doesn't support string interpolation, use this instead:

conn.ConnectionString = "Server=" & ServerMySQL & ";Port=" & PortMySQL & ";Database=" & DBNameMySQL & ";Uid=" & UserNameMySQL & ";Pwd=" & PwdMySQL & ";"

We removed the single quotes and used the standard Uid shorthand instead of user id (both work, but Uid is more widely used).

2. Confirm Registry Settings Are Loading Correctly

Your getData() method falls back to "temp" values if registry access fails, but you have no way to verify if the actual settings are being pulled. Add debug output to check:

Sub getData()
    Dim AppName As String = Application.ProductName
    Try
        DBNameMySQL = GetSetting(AppName, "DBSection", "DB_Name", "temp")
        ServerMySQL = GetSetting(AppName, "DBSection", "DB_IP", "temp")
        PortMySQL = GetSetting(AppName, "DBSection", "DB_Port", "temp")
        UserNameMySQL = GetSetting(AppName, "DBSection", "DB_User", "temp")
        PwdMySQL = GetSetting(AppName, "DBSection", "DB_Password", "temp")
        
        // Add this line to check values in debug mode
        Debug.WriteLine($"Loaded Settings: Server={ServerMySQL}, Port={PortMySQL}, DB={DBNameMySQL}, User={UserNameMySQL}")
    Catch ex As Exception
        MsgBox("System registry was not established, you can set/save these settings by pressing F1", MsgBoxStyle.Information)
        Debug.WriteLine($"Registry Load Error: {ex.Message}")
    End Try
End Sub

If you see "temp" in the debug output, run SaveData() first to store your actual database credentials in the registry.

3. Verify Network & Server Accessibility

  • Ping the MySQL server IP from your machine to confirm basic network connectivity.
  • Check that the MySQL port (default 3306) isn't blocked by a firewall on your local machine or the server.
  • Test the same credentials with a MySQL client like MySQL Workbench—if that fails, the issue is with the server or credentials, not your code.

4. Get Specific Error Details

Your current catch block only shows a generic message. Modify it to display the full exception info, which will tell you exactly what's wrong (bad credentials, server not found, etc.):

Catch ex As Exception
    MsgBox($"Connection Failed: {ex.Message}{vbCrLf}{ex.InnerException?.Message}", MsgBoxStyle.Critical, "Database Error")
End Try

5. Fix Connection Object Lifecycle

Using a global conn object can lead to unexpected state issues. Instead, create a new connection instance each time and use Using to ensure it's properly cleaned up:

Public Sub ConnDB()
    Using conn As New MySqlConnection($"Server={ServerMySQL};Port={PortMySQL};Database={DBNameMySQL};Uid={UserNameMySQL};Pwd={PwdMySQL};")
        Try
            conn.Open()
            MsgBox("Connection established successfully!", MsgBoxStyle.Information)
            // Handle your login logic here while the connection is open
        Catch ex As Exception
            MsgBox($"Connection Failed: {ex.Message}{vbCrLf}{ex.InnerException?.Message}", MsgBoxStyle.Critical, "Database Error")
        End Try
    End Using // Connection auto-closes and disposes here
End Sub

6. Check MySQL Connector Installation

Make sure you have the correct version of MySQL Connector/NET installed for your project. If using NuGet, verify the MySql.Data package is up to date and properly referenced.

Start with fixing the connection string—this is the most likely culprit. If you get a specific error message after updating the error handling, share it and we can narrow things down further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 07:59:00