繁体   English   中英

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

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

我正在使用 Visual Studio 2019 制作一个工具。当我尝试单击注册按钮时没有出现错误。 但是当我打开数据库并刷新表时,data.table中没有数据。

非常感谢对此问题的任何支持。 谢谢你。

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);
        }
}

这将修复原始版本中的许多小问题,有些不是那么小,并且作为奖励应该运行得更快。 也就是说,它还有很多代码直接输入到回复 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();
}

您错误地设置了命令参数:尝试这样的事情:

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

此外,使用两个 Executenonquerys,一个用于注册,另一个用于其他表。

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM