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

为何注册用户无法保存至数据库?登录提示无效凭证求助

用户注册后登录提示无效凭证问题

我已经折腾这个问题好一阵子了,除了注册用户登录时提示无效凭证外,其他功能都正常,这说明用户数据没成功保存。之前功能是好的,不知道为啥突然不行了。

以下是我的代码:

using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace SchoolManagementApplication
{
    public partial class LoginDialog : Form
    {
        public LoginDialog()
        {
            InitializeComponent();
        }

        private bool VerifyUserCredentials(string username, string password)
        {
            bool isValidUser = false;

            // Connection string
            string connectionString = Properties.Settings.Default.UnPConnectionString;

            // SQL query
            string query = "SELECT COUNT(*) FROM [Table2] WHERE Username = @Username AND Password = @Password";

            // Create a new connection
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // Create a new command
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    // Add parameters to the query
                    command.Parameters.AddWithValue("@Username", username);
                    command.Parameters.AddWithValue("@Password", password);
                    // Open the connection
                    connection.Open();
                    // Execute the query
                    int result = (int)command.ExecuteScalar();
                    // Check if the result is greater than 0
                    if (result > 0)
                    {
                        isValidUser = true;
                    }
                    connection.Close();
                }
            }
            return isValidUser;
        }

        public void AddUser(string username, string password)
        {
            string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\shayan.homaiesfahan\\Desktop\\SchoolManagementApplication\\SchoolManagementApplication\\bin\\Debug\\Unp.mdf;Integrated Security=True";

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // insert the new user into the table
                string insertSql = "INSERT INTO [Table2] (Username, Password) VALUES (@Username, @Password)";
                using (SqlCommand insertCommand = new SqlCommand(insertSql, connection))
                {
                    insertCommand.Parameters.AddWithValue("@Username", username);
                    insertCommand.Parameters.AddWithValue("@Password", password);
                    insertCommand.ExecuteNonQuery();
                }
                connection.Close();
            }
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            // Get the entered username and password
            string username = tbxUsername.Text;
            string password = tbxPassword.Text;

            // Verify the user credentials
            if (VerifyUserCredentials(username, password))
            {
                MessageBox.Show(string.Format("Welcome: {0}", username));
                // Code to open the main application goes here
                this.Hide();
                MainInterface MI = new MainInterface();
                MI.Show();
            }
            else
            {
                MessageBox.Show("Invalid credentials. Please try again.");
                //// Clear the textboxes
                tbxUsername.Text = "";
                tbxPassword.Text = "";
            }
        }


        private void Btn_register_Click(object sender, EventArgs e)
        {
            string username = tbxUsername.Text;
            string password = tbxPassword.Text;

            // Verify that the username and password are not empty
            if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(password))
            {
                // Call the AddUser method
                AddUser(username, password);

                // Show a message that the user has been registered
                MessageBox.Show("You have been successfully registered!");

                // Clear the textboxes
                tbxUsername.Text = "";
                tbxPassword.Text = "";
            }
            else
            {
                // Show a message that the username and password are required
                MessageBox.Show("Username and password are required.");
            }
        }

        private void btnCancel2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

排查方向及修复建议

  • 连接字符串不一致:注册方法AddUser用的是硬编码的本地DB路径,而登录验证用的是配置文件中的连接字符串,二者大概率指向不同数据库文件。把AddUser里的连接字符串改成Properties.Settings.Default.UnPConnectionString,统一指向同一个DB。

  • 数据库文件被覆盖:如果项目中Unp.mdf的「复制到输出目录」属性设为「始终复制」,每次编译都会用项目根目录的空DB覆盖Debug目录的DB,导致之前注册的数据丢失。右键Unp.mdf→属性,将该选项改为「如果较新则复制」或「不复制」。

  • 未捕获注册异常:AddUser方法没有异常捕获逻辑,可能注册时已抛出错误(如DB权限不足、表结构变更)但未被发现。给AddUser添加try-catch块,捕获异常并提示具体错误信息,方便定位问题。

  • 直接验证数据:打开连接字符串指向的数据库文件,查看Table2中是否存在注册的用户数据,同时确认表字段(Username、Password)的类型、长度是否与代码匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:32:28