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

如何将注册用户保存至数据库?窗体关闭后注册数据丢失问题排查

注册用户无法持久化到数据库的问题

我尝试通过SQL语句向数据表中添加用户,不关闭LoginDialog窗体时功能正常,但关闭窗体后再次登录会提示用户未注册。代码运行无报错,但注册的用户数据未被持久化保存至数据库。

相关代码

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 isLogin)
        {
            bool isValidUser = false;

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

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

            // SQL query for registration
            string registerQuery = "INSERT INTO [Table2] (Username, Password) VALUES (@Username, @Password)";

            // Create a new connection
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                // Open the connection
                connection.Open();

                // If the user wants to login
                if (isLogin)
                {
                    // Create a new command
                    using (SqlCommand command = new SqlCommand(loginQuery, connection))
                    {
                        // Add parameters to the query
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        // Execute the query
                        int result = (int)command.ExecuteScalar();
                        // Check if the result is greater than 0
                        if (result > 0)
                        {
                            isValidUser = true;
                        }
                    }
                }
                // If the user wants to register
                else
                {
                    // Create a new command
                    using (SqlCommand command = new SqlCommand(registerQuery, connection))
                    {
                        // Add parameters to the query
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        // Execute the query
                        int result = command.ExecuteNonQuery();
                        // Check if the result is greater than 0
                        if (result > 0)
                        {
                            isValidUser = true;
                        }
                    }
                }
            }

            return isValidUser;
        }

        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, true))
            {
                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)
        {
            // Get the entered username and password
            string username = tbxUsername.Text;
            string password = tbxPassword.Text;
            // Verify the user credentials
            if (VerifyUserCredentials(username, password, false))
            {
                MessageBox.Show(string.Format("Successful registration: {0}", username));
            }
            else
            {
                MessageBox.Show("Registration failed. Please try again.");
            }
        }
    }
}

问题排查与解决办法

  • 数据库文件被自动覆盖
    这是最常见的原因:如果你的数据库文件(如.mdf)放在项目目录下,Visual Studio默认会在每次编译时将原始数据库文件复制到输出目录(如bin/Debug),覆盖掉之前注册用户后的数据库文件。
    解决步骤:右键项目中的数据库文件 → 选择“属性” → 将“复制到输出目录”选项改为如果较新则复制或不复制。

  • 连接字符串指向临时数据库
    检查Properties.Settings.Default.UnPConnectionString的内容,确认连接的是固定路径的数据库文件,而非临时生成的副本。比如使用AttachDbFilename时,避免使用相对路径或自动生成的临时路径,改用绝对路径或指向项目中固定的数据库文件。

  • 检查数据库表约束
    确认Table2表的Username字段没有设置重复约束(如主键、唯一索引),如果注册时输入了重复用户名,ExecuteNonQuery会返回0,此时会提示注册失败,但你当前场景是注册成功后重启失效,这条可能性较低,但可通过数据库直接查询确认。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:25:22