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

C# WinForms连接远程PostgreSQL服务器失败问题求助

无法连接远程PostgreSQL服务器的问题排查

我在VS Community的C# WinForms项目中,使用Npgsql NuGet包尝试连接朋友笔记本上的PostgreSQL服务器时,出现无法连接到127.0.0.1:5432的错误,无法完成登录或用户注册操作。但朋友在本地运行该程序时,可正常从数据库读取数据并完成登录、注册。

相关代码

ConnectionManager类代码

public static class ConnectionManager
{
    private static NpgsqlConnection connection;

    public static NpgsqlConnection Connection
    {
        get { return connection; }
    }

    public static NpgsqlConnection GetNpgsqlConnection()
    {
        string connectionString = "Host=localhost;Username=postgres;Password=Kirkdave123;Database=MSAD_Project";

        connection = new NpgsqlConnection(connectionString);
        connection.Open();

        return connection;
    }

    public static void TurnoffNpgConnection()
    {
        connection.Close(); 
    }
}

登录窗体代码

public partial class LoginForm : Form
{
    private bool isFirstClick = true;
    public LoginForm()
    {
        InitializeComponent();
    }

    private void LoginBtn_Click(object sender, EventArgs e)
    {
        // 验证用户名密码是否为合法用户或管理员

        string username = UserName_txtbx.Text;
        string password = Password_txtbx.Text;

        if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
        {
            MessageBox.Show("请输入用户名和密码。", "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            return;
        }

        try
        {
            using (NpgsqlConnection connection = ConnectionManager.GetNpgsqlConnection())
            {
                string query = "SELECT COUNT(*) FROM public.\"User_Account\" WHERE \"Username\" = @username AND \"Password\" = @password";
                using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
                {
                    command.Parameters.AddWithValue("@username", username);
                    command.Parameters.AddWithValue("@password", password);

                    int count = Convert.ToInt32(command.ExecuteScalar());
                    if (count > 0)
                    {
                        MessageBox.Show("登录成功!", "登录", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        var dashboard = new DashboardForm();
                        dashboard.Show();
                        this.Hide();
                    }
                    else
                    {
                        MessageBox.Show("用户名或密码错误。", "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("登录过程中发生错误:" + ex.Message, "登录错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

    private void ForgotPasswordLinkLbl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        var forgotpassword = new ForgotPasswordForm();
        forgotpassword.Show();
        this.Hide();
    }

    private void RegisterLinkLbl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        var register = new RegisterForm();
        register.Show();
        this.Hide();
    }

    private void UserName_txtbx_Click(object sender, EventArgs e)
    {
        UserName_txtbx.Clear();
    }

    private void Password_txtbx_Click(object sender, EventArgs e)
    {
        Password_txtbx.Clear();
    }
}

注册窗体代码

public partial class RegisterForm : Form
{
    private Random random = new Random();

    public RegisterForm()
    {
        InitializeComponent();
    }

    private void GobackBtn_Click(object sender, EventArgs e)
    {
        var login = new LoginForm();
        login.Show();
        this.Hide();
    }


    private void RegisterBtn_Click(object sender, EventArgs e)
    {
        bool CheckBox1Checked = CheckBox1.Checked;

        if (!CheckBox1Checked)
        {
            MessageBox.Show("注册前请阅读并同意政策条款");
        }

        else if (!ValidateFormFields())
        {
            MessageBox.Show("请填写所有必填字段。", "注册错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        else
        {
            string username = UsernameTbx.Text;
            string password = PasswordTbx.Text;
            string email = EmailTbx.Text;
            string phone = PhoneTbx.Text;
            string lastName = LNametxtbx.Text;
            string firstName = Fnametxtbx.Text;
            int age = Convert.ToInt32(AgecomboBox.SelectedItem);
            string gender = GcomboBox.SelectedItem.ToString();

            int userID = GenerateRandomUserID();

            try
            {
                using (NpgsqlConnection connection = ConnectionManager.GetNpgsqlConnection())
                {
                    string query = "INSERT INTO public.\"User_Account\" (\"UserID\", \"Lastname\", \"Firstname\", \"Gender\", \"Age\", \"Email\", \"Phonenumber\", \"Username\", \"Password\") " +
                        "VALUES (@userID, @lastname, @firstname, @gender, @age, @email, @phone, @username, @password)";

                    using (NpgsqlCommand command = new NpgsqlCommand(query, connection))
                    {
                        command.Parameters.AddWithValue("@userID", userID);
                        command.Parameters.AddWithValue("@lastname", lastName);
                        command.Parameters.AddWithValue("@firstname", firstName);
                        command.Parameters.AddWithValue("@gender", gender);
                        command.Parameters.AddWithValue("@age", age);
                        command.Parameters.AddWithValue("@email", email);
                        command.Parameters.AddWithValue("@phone", phone);
                        command.Parameters.AddWithValue("@username", username);
                        command.Parameters.AddWithValue("@password", password);

                        int rowsAffected = command.ExecuteNonQuery();

                        if (rowsAffected > 0)
                        {
                            MessageBox.Show("注册成功!即将跳转到登录页面", "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            var login = new LoginForm();
                            login.Show();
                            this.Hide();
                        }
                        else
                        {
                            MessageBox.Show("注册失败!", "注册错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("注册过程中发生错误:" + ex.Message, "注册错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                ConnectionManager.TurnoffNpgConnection();
            }
        }

    }

    private int GenerateRandomUserID()
    {
        return random.Next(1000000, 9999999);
    }

    private bool ValidateFormFields()
    {
        if (string.IsNullOrWhiteSpace(UsernameTbx.Text) ||
            string.IsNullOrWhiteSpace(PasswordTbx.Text) ||
            string.IsNullOrWhiteSpace(EmailTbx.Text) ||
            string.IsNullOrWhiteSpace(PhoneTbx.Text) ||
            string.IsNullOrWhiteSpace(LNametxtbx.Text) ||
            string.IsNullOrWhiteSpace(Fnametxtbx.Text) ||
            AgecomboBox.SelectedItem == null ||
            GcomboBox.SelectedItem == null)
        {
            return false;
        }
        return true;
    }

    private void pictureBox6_Click(object sender, EventArgs e)
    {

    }
}

运行错误提示

程序运行时弹出错误提示:无法连接到服务器:连接尝试失败,因为连接方在一段时间后没有正确答复,或者连接的主机没有反应。 127.0.0.1:5432

已尝试的解决操作

  • 修改PostgreSQL的pg_hba.conf和postgresql.conf配置文件
  • 在朋友的笔记本上配置Windows Defender防火墙的入站规则,允许PostgreSQL端口通行

疑问

请问这是C#代码问题还是网络连通性问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 12:57:01