简体   繁体   English

插入登录和注册数据未显示在 SQL 服务器数据库表 Visual Studio 2019

[英]Insert login and registration data not show in SQL Server database table Visual Studio 2019

I'm making a tool using Visual Studio 2019. When I tried to click registration button and there's no errors.我正在使用 Visual Studio 2019 制作一个工具。当我尝试单击注册按钮时没有出现错误。 But when I open the database and refresh the table, there's no data in the data.table.但是当我打开数据库并刷新表时,data.table中没有数据。

Any support for this issue much appreciated.非常感谢对此问题的任何支持。 Thank you.谢谢你。

private void submitBtn_Click(object sender, EventArgs e)
{
        //connection string
        SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\ImageSteganography_2\ImageSteganography\Database1.mdf;Integrated Security=True");

        // Connection open here   
        conn.Open();

        SqlCommand cmd = new SqlCommand();

        if (repeatPassBox.Text != string.Empty || passBox.Text != string.Empty || contactBox.Text != string.Empty || emailBox.Text != string.Empty || userBox.Text != string.Empty)
        {
            //Email Address
            if (validate_email.IsMatch(emailBox.Text) != true)
            {
                MessageBox.Show("Invalid Email Address!", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                emailBox.Focus();
            }
            // Contacts
            else if (validate_contact.IsMatch(contactBox.Text) != true)
            {
                MessageBox.Show("Contact accept numbers only (10 digit).", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                contactBox.Focus();
            }
            // Password
            else if (validate_password.IsMatch(passBox.Text) != true)
            {
                MessageBox.Show("Password must be atleast 8 to 15 characters. It should contain at least one Upper case and numbers.", "Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                passBox.Focus();
            }
            // Repeat Password
            else if (passBox.Text != repeatPassBox.Text)
            {
                MessageBox.Show("Please enter both password same ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } 
            else
            {
                cmd = new SqlCommand("select * from Login where username='" + userBox.Text + "'", conn);
                
                SqlDataReader dr = cmd.ExecuteReader();

                if (dr.Read())
                {
                    dr.Close();
                    MessageBox.Show("Username already exists - please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    dr.Close();
                    cmd = new SqlCommand("insert into Registration values (@username, @email, @contact, @password, @repeatPassword)", conn);
                    cmd.Parameters.AddWithValue("username", userBox.Text);
                    cmd.Parameters.AddWithValue("email", emailBox.Text);
                    cmd.Parameters.AddWithValue("contact", contactBox.Text);
                    cmd.Parameters.AddWithValue("password", passBox.Text);
                    cmd.Parameters.AddWithValue("repeatPassword", repeatPassBox.Text);
                    

                    cmd = new SqlCommand("insert into Login values(@username,@password)", conn);
                    cmd.Parameters.AddWithValue("username", userBox.Text);
                    cmd.Parameters.AddWithValue("password", passBox.Text);
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("Register successful. Please login now.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Hide();
                    LOGIN f1 = new LOGIN();
                    f1.ShowDialog();
                }
                conn.Close();
            }
        }
        else
        {
            MessageBox.Show("All input fields cannot be blank.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
}

This will fix a LOT of small issues in the original, some not-so-small, and should run faster as a bonus.这将修复原始版本中的许多小问题,有些不是那么小,并且作为奖励应该运行得更快。 That said, it's also a lot of code typed directly into the reply window, so it likely has a bug or five of its own still to work out:也就是说,它还有很多代码直接输入到回复 window 中,因此它可能还有一个或五个自己的错误有待解决:

private (string, Control) CheckRegistrationData()
{
    //Email Address
    if (emailBox.Text == "" || validate_email.IsMatch(emailBox.Text) != true)
    {
        return ("Invalid Email Address!", emailBox);
    }
    
    //Contacts
    if (contactBox.Text == "" || validate_contact.IsMatch(contactBox.Text) != true)
    {
        return ("Contact accept numbers only (10 digit).", contactBox);
    }

    // Password
    if (passBox.Text == "" || validate_password.IsMatch(passBox.Text) != true)
    {
        return ("Password must be atleast 8 to 15 characters. It should contain at least one Upper case and numbers.");
    }

    //Repeat Password
    if (repeatPassBox.Text == "" || passBox.Text != repeatPassBox.Text)
    {
        return ("Please enter both password same ", repeatPassBox);
    }
     
    return ("", null);
}

private void submitBtn_Click(object sender, EventArgs e)
{
     var validationResult = CheckRegistrationData();
     if (!string.IsNullOrEmpty(validationResult.Item1))
     {
         MessageBox.Show(validationResult.Item1, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
         if (validationResult.Item2 is Control)
         {
             valiadtionResult.Item2.Focus();
         }
         return;
     }
     
     // VALIDATION COMPLETE

     string SQL = @"
IF EXISTS(SELECT 1 FROM Login WHERE Username= @username )
BEGIN
    RAISERROR('Username Already exist',16,1);
END
ELSE
BEGIN
    INSERT INTO Registration (Username, Email, Contact, PasswordHash)
    VALUES (@username,@email,@contact,@passwordHash);
    INSERT INTO Login (UserName, PasswordHash) VALUES (@username,@passwordHash);
END
";

    using (var conn = new SqlConnection(@"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = C:\ImageSteganography_2\ImageSteganography\Database1.mdf; Integrated Security = True"))
    using (var cmd = new SqlCommand(SQL, conn))
    {   //Much better to replace AddWithValue() with Add() and provide explicit type information about the database columns.     
        cmd.Parameters.AddWithValue("@username", userBox.Text);
        cmd.Parameters.AddWithValue("@email", emailBox.Text);
        cmd.Parameters.AddWithValue("@contact", contactBox.Text);
        cmd.Parameters.AddWithValue("@passwordHash", BCrypt.Net.BCrypt.HashPassword(passBox.Text)); //Based on BCrypt.Net Nuget package

        try 
        {                     
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch(SqlException ex) when (ex.Errors[0].Class == 16)
        {
            MessageBox.Show("Username Already exist please try another ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            return; 
        }
        catch(Exception ex)
        {
            MessageBox.Show($"Error trying to create registration: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            return;
        }
    }

    MessageBox.Show("Register successful. Please login now.", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
    this.Hide();
    var f1 = new LOGIN();
    f1.ShowDialog();
}

You are setting the command parameters incorrectly: Try something like this:您错误地设置了命令参数:尝试这样的事情:

cmd.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = userBox.Text;

Also, use two Executenonquerys one for registration and other for other table.此外,使用两个 Executenonquerys,一个用于注册,另一个用于其他表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 插入和注册数据未显示在数据库表 Visual Studio 2019 中 - Insert and Registration data not show in database table visual studio 2019 注册表单Visual Studio中的SQL Server数据库问题 - Issue with SQL Server database in Registration form Visual Studio 在 SQL 中保存注册页面数据并在 Visual Basic (Visual Studio 2019) 中验证并重定向到主页 - Save registration page data in SQL and validate and redirect to home page in Visual Basic (Visual Studio 2019) 具有本地SQL Server数据库的Visual Studio登录页面 - Visual Studio Login Page with local SQL server database 使用Visual Studio 2017在SQL数据库中插入数据 - Insert data in SQL Database using Visual Studio 2017 无法在Visual Studio 2015中将表添加到SQL Server数据库 - Can't add table to SQL Server database in Visual Studio 2015 Visual Studio 2019 c-sharp 中检索 SQL Server 2019 表列列表的 ExecuteScalar 方法错误地按 ASCII 排序 - ExecuteScalar method to retrieve SQL Server 2019 table column list in Visual Studio 2019 c-sharp is incorrectly ASCII sorted Visual Studio 服务器资源管理器显示表数据为空白 - Visual Studio Server Explorer show table data is blank 如何将数据表插入SQL Server数据库表? - How to insert a data table into SQL Server database table? 在Visual Studio中使用数据连接来探索SQL Server Express数据库 - Using data connections in Visual Studio to explore SQL Server Express database
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM