C#窗体程序连接SQL Server数据库实现账号登录、账号注册、修改密码、账号注销和实名认证(不定时更新)

  • Post author:
  • Post category:其他



这是本人用Visual Studio2019做的一个C#窗体登录程序,如标题所示,它包含了账号登录、注册账号、修改密码、注销账号和实名认证五个功能。对于有一定基础知识的小伙伴来说,应该不算太难,里面有注释说明,可能咋一看感觉代码运行的逻辑有点乱,不过没关系,相信对你会有所帮助。以下是详细的操作过程。



一、配置数据库文件和程序代码


1、由于这个登录程序连接了SQL Server数据库,所以需要配置一下相关数据,创建一个“账号登录”数据库,新建一个“登录注册表”和“实名信息表”,并记住这个服务器名称,等下会用到,如下图所示。

在这里插入图片描



登录注册表设置两个列名:username(账号)和password(密码)以及对应的数据类型(可自定义)。

在这里插入图片描述



实名信息表要设置3个列名,分别是:username(账号)、Name(姓名)、IDcard(身份证号)。设置username列名是为了关联这两张表。

实名信息表列表格式


SQL查询显示结果,password和userpwd(即username+password)均显示为密文;如果账号未实名,则Name和IDcard两栏没有数据。

在这里插入图片描述


2、然后打开VS2019,新建一个窗体程序(我新建的窗体是CT12),在里面设置一下App.config的SQL数据库连接信息,如下图所示。

在这里插入图片描述


App.config里面的代码格式:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8" />
	</startup>
	<connectionStrings>
		<add name="sqlserver" connectionString="server=SQLEXPRESS;database=账号登录;integrated security = true;"/>
		//这是以windows身份验证登录连接,SQLEXPRESS是服务器名称,“账号登录”是新建的数据库名称.
	</connectionStrings>
</configuration>



二、配置C#窗体控件布局和源代码


该登录程序包含了6个窗体,分别为:Form1——登录界面、Form2——注册界面、Form3——主界面、Form4——修改密码界面、Form5——账号注销界面、Form6——实名认证界面。


这里还要新创建一个公共类Encrypt1.cs,在这些窗体中都会调用到。

using System;
using System.Security.Cryptography;
using System.Text;

namespace CT12
{
    class Encrypt1
    {
        public  string EncryptPassword(string userpwd)
        {
            byte[] saltBytes = Encoding.UTF8.GetBytes(userpwd); // 自定义盐值,用于固定加密结果
            byte[] passwordBytes = Encoding.UTF8.GetBytes(userpwd + Convert.ToBase64String(saltBytes));
            byte[] hashedBytes;
            using (SHA256 sha256 = SHA256.Create())
            {
                hashedBytes = sha256.ComputeHash(passwordBytes);
            }
            string hashedPassword = Convert.ToBase64String(hashedBytes);
            int length = hashedPassword.Length;
            if (length % 2 == 0) // 如果加密后的密码长度为偶数,则(加密后的密码长度/2)并输出
            {
                hashedPassword = hashedPassword.Substring(0, length / 2);
            }
            else // 如果为奇数,则(加密后的密码-1)/2并输出
            {
                hashedPassword = hashedPassword.Substring(0, (length - 1) / 2);
            }
            return hashedPassword;
        }
    }
}



注意:由于连接了SQL数据库,这5个窗体之间数据相互传递、相互关联,如果只截取一段窗体代码运行,则会直接报错。



1、窗体Form1:账号登录界面


label1——账号,label2——密码,

textBox1——对应账号输入,textBox2——对应密码输入,

button1——登录,button2——重置,

button3——退出,button4——注册。

checkBox1——是否显示密码


窗体Form1的控件布局:

Form1窗体控件布局


窗体Form1源代码

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;
using System.Drawing;
using System.ComponentModel;
using System.Security.Cryptography;
using System.Text;
using System.Diagnostics;

namespace CT12
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Text = "账号登录";
            ScreenSize();
            textBox2.PasswordChar = '*';//密码显示为"*"
        }

        public void ScreenSize()    //设置窗体样式和居中显示
        {
            int x = Screen.GetBounds(this).Width;
            int y = Screen.GetBounds(this).Height;
            this.MinimumSize = new Size(x / 2, y / 2);
            this.MaximumSize = new Size(x / 2, y / 2);
            this.CenterToParent();
            this.CenterToScreen();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            ScreenSize();   //调用函数
            this.ActiveControl = textBox1;  //焦点在控件textBox1上面
        }

        private void Button4_Click(object sender, EventArgs e) //跳转注册界面
        {
            this.Hide();
            Form2 sd = new Form2();
            sd.Show();
        }

        private void Button2_Click(object sender, EventArgs e)      //重置登录信息
        {
            textBox1.Text = "";
            textBox2.Text = "";
            this.ActiveControl = textBox1;
        }

        private void button3_Click(object sender, EventArgs e)//强制退出窗体程序
        {
            Process.GetCurrentProcess().Kill();
        }

        private static readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;     //创建数据库连接

        public static string username;  //设置Form1的一个参数,登录成功后将显示在主界面Form3
        public static string password;

        private void Button1_Click(object sender, EventArgs e)  //登录代码
        {
            Encrypt1 SHA256 = new Encrypt1();//调用该加密类
            if (textBox1.Text.Equals(""))
            {
                MessageBox.Show("账号不得为空!", "提示");
                this.ActiveControl = textBox1;
            }
            else if (textBox2.Text.Equals(""))
            {
                MessageBox.Show("密码不得为空!", "提示");
                this.ActiveControl = textBox2;
            }
            else
            {
                using (SqlConnection conn = new SqlConnection(Stu))
                {
                    conn.Open();
                    string sql = "select count(*) from 登录注册表 where username=@username";
                    SqlCommand cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@username", textBox1.Text.Trim());
                    int count = Convert.ToInt32(cmd.ExecuteScalar());
                    if (count <= 0)
                    {
                        DialogResult dr = MessageBox.Show("账号不存在,是否选择注册一个新账号?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
                        if (dr == DialogResult.OK)
                        {
                            this.Hide();
                            Form2 er = new Form2();
                            er.Show();
                            conn.Close();
                        }
                        else
                        {
                            textBox1.Text = "";
                            textBox2.Text = "";
                            this.ActiveControl = textBox1;
                        }
                        return;
                    }
                    // 验证用户密码
                    sql = "SELECT COUNT(1) FROM 登录注册表 WHERE username=@username AND password=@password";
                    cmd = new SqlCommand(sql, conn);
                    cmd.Parameters.AddWithValue("@username", textBox1.Text.Trim());
                    cmd.Parameters.AddWithValue("@password", SHA256.EncryptPassword(textBox1.Text.Trim()+textBox2.Text.Trim()));
                    count = Convert.ToInt32(cmd.ExecuteScalar());
                    if (count <= 0)
                    {
                        MessageBox.Show("账号密码错误!");
                        textBox2.Text = "";
                        return;
                    }
                    // 账号登录成功
                    MessageBox.Show("登录成功!");
                    username = textBox1.Text.Trim();       //将textBox1的值赋给参数username
                    password = textBox2.Text.Trim();        //将textBox2的值赋给参数password
                    conn.Close();
                    this.Hide();
                    Form3 sd = new Form3();
                    sd.Show();         //显示主界面Form3
                }
            }
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)   //是否显示密码输入为“*”
        {
            if (checkBox1.Checked)
            {
                textBox2.PasswordChar = '\0';
            }
            else
            {
                textBox2.PasswordChar = '*';
            }
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }     
    }
}



窗体Form1运行效果截图

账号登录成功


在这里插入图片描述


在这里插入图片描述




2、窗体Form2:账号注册界面


label1——新用户名,label2——用户密码,label3——确认密码

textBox1(对应新用户名),textBox2(对应用户密码),textBox3(对应确认密码)

button1——确认,button2——重置,button3——返回


窗体Form2的控件布局

在这里插入图片描述


窗体Form2源代码

using System;
using System.ComponentModel;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace CT12
{
   public partial class Form2 : Form
    {
      public Form2()
        {
            InitializeComponent();
            this.Text = "账号注册";
            ScreenSize();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            ScreenSize();
            textBox2.PasswordChar = '*';    //textBox2——用户密码显示为"*"
            textBox3.PasswordChar = '*';    //textBox3——确认密码显示为"*"
            this.ActiveControl = textBox1;  //焦点在输入框textBox1上
        }

       private void ScreenSize()    //设置窗体大小尺寸和居中显示
        {
            int x = Screen.GetBounds(this).Width;       //获取屏幕宽度
            int y = Screen.GetBounds(this).Height;      //获取屏幕高度
            this.MinimumSize = new Size(x / 2, y / 2);      //设置窗口最小尺寸
            this.MaximumSize = new Size(x / 2, y / 2);      //设置窗口最大尺寸
            this.CenterToParent();
            this.CenterToScreen();
        }

        private void Button2_Click(object sender, EventArgs e)  //重置输入框信息
        {
            textBox1.Text = "";
            textBox2.Text = "";
            textBox3.Text = "";
            this.ActiveControl = textBox1;
        }

        private void Button3_Click(object sender, EventArgs e)  //返回登录界面Form1
        {
            this.Hide();
            Form1 sd = new Form1();
            sd.Show();
        }

        readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;

        private void Button1_Click(object sender, EventArgs e)
        {
            Encrypt1 SHA256 = new Encrypt1();
            if (textBox1.Text.Equals(""))
            {
                MessageBox.Show("注册账号不得为空!", "提示");
            }
            else if (textBox2.Text.Equals(""))
            {
                MessageBox.Show("注册账号密码不得为空!", "提示");
            }
            else if (textBox3.Text.Equals("") || !textBox2.Text.Equals(textBox3.Text))
            {
                MessageBox.Show("请重新确认密码", "提示");
                textBox2.Text = "";
                textBox3.Text = "";
            }
            /*else if(textBox1.Text.Length<8)
            {
                MessageBox.Show("请输入8位以上的新用户名!", "提示");
                textBox1.Text = "";
            }
            else if (Regex.IsMatch(textBox2.Text.ToString(), @"^\w+_$") == false&&(textBox2.Text.Length<8||textBox2.Text.Length>16))
            {
                MessageBox.Show("请输入8~16位由字母、数字和下划线组成的密码!");
                textBox2.Text = "";
                textBox3.Text = "";
            }*/
            else
            {
                using (SqlConnection conn = new SqlConnection(Stu))
                {
                    conn.Open();
                    SqlCommand command = new SqlCommand
                    {
                        Connection = conn,
                        CommandText = "SELECT COUNT(*) FROM 登录注册表 WHERE username = @username"
                    };
                    command.Parameters.AddWithValue("@username", textBox1.Text.Trim());
                    int count = (int)command.ExecuteScalar();
                    if (count > 0)
                    {
                        MessageBox.Show("账号已注册!");
                        textBox1.Text = "";
                        textBox2.Text = "";
                        textBox3.Text = "";
                        this.ActiveControl = textBox1;
                        return;
                    }
                    conn.Close();
                }

                using (SqlConnection connection = new SqlConnection(Stu))
                {
                    try
                    {
                        connection.Open();
                        SqlCommand command = new SqlCommand
                        {
                            Connection = connection,
                            CommandText = "INSERT INTO 登录注册表 (username, password) VALUES (@username, @password)"
                        };
                        command.Parameters.AddWithValue("@username", textBox1.Text);
                        command.Parameters.AddWithValue("@password", SHA256.EncryptPassword(textBox1.Text.Trim()+textBox2.Text.Trim()));
                        command.ExecuteNonQuery();
                        MessageBox.Show("账号注册成功!");
                        this.Hide();
                        Form1 sd = new Form1();
                        sd.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                }
            }
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)   //textBox2文本框输入显示为"*"
        {
            if (checkBox1.Checked)
                textBox2.PasswordChar = '\0';
            else
                textBox2.PasswordChar = '*';
        }

        private void CheckBox2_CheckedChanged(object sender, EventArgs e)   //textBox3文本框输入为"*"
        {
            if (checkBox2.Checked)
                textBox3.PasswordChar = '\0';
            else
                textBox3.PasswordChar = '*';
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        private void Form2_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}



窗体Form2运行效果截图

账号注册成功


账号已注册




3、窗体Form3:主界面


checkBox1——当前账号,Label1——显示账号

textBox1——显示姓名,textBox2——显示身份证号

Button1——修改密码,Button2——注销账号,Button5——实名认证,

Button3——返回,Button4——退出


窗体Form3的控件布局

在这里插入图片描述


窗体Form3的源代码

using System;
using System.ComponentModel;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace CT12
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
            this.Text = "账号信息";
            ScreenSize();
        }

        public void ScreenSize()
        {
            int x = Screen.GetBounds(this).Width;
            int y = Screen.GetBounds(this).Height;
            this.MinimumSize = new Size(x / 2, y / 2);
            this.MaximumSize = new Size(x / 2, y / 2);
            this.CenterToParent();
            this.CenterToScreen();
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            ScreenSize();
            ShowUser(Form1.username);
            this.HideDcard(Form1.username);
            ShowName();
        }

        public void ShowName()//在主界面显示实名信息
        {
            using (SqlConnection conn = new SqlConnection(Stu))
            {
                // 打开连接
                conn.Open();
                // 查询该账户是否实名认证
                string query = "SELECT Name, IDcard FROM 实名信息表 WHERE username = @username ";
                using (SqlCommand command = new SqlCommand(query, conn))
                {
                    command.Parameters.AddWithValue("@username", Form1.username);
                    SqlDataReader reader = command.ExecuteReader();
                    if (reader.Read())
                    {
                        // 如果已经实名认证,则显示姓名
                        textBox2.Text = reader["Name"].ToString();
                    }
                    else
                    {
                        textBox2.Text = "";
                    }
                    reader.Close();
                }
            }
        }

        private void Button1_Click(object sender, EventArgs e)  //跳转窗体Form4:修改密码界面
        {
            this.Hide();
            Form4 df = new Form4();
            df.Show();
        }

        private void Button2_Click(object sender, EventArgs e)  //跳转窗体Form5:注销账号界面
        {
            this.Hide();
            Form5 sd = new Form5();
            sd.Show();
        }

        private void Button4_Click(object sender, EventArgs e)  //强制退出所有窗口程序和线程
        {
            Process.GetCurrentProcess().Kill();
        }

        private void Button3_Click(object sender, EventArgs e)  //返回窗体Form1:登录界面
        {
            DialogResult dr = MessageBox.Show("是否返回登录界面?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            if (dr == DialogResult.Yes)
            {
                this.Hide();
                Form1 sdd = new Form1();
                sdd.Show();
            }
        }

        private void Button5_Click_1(object sender, EventArgs e)
        {
            this.Hide();
            Form6 asd = new Form6();
            asd.Show();
        }

        public void ShowUser(string text)
        {
            char StarChar = '*';
            string value = text;
            int startlen = 1, endlen = 1;
            int lenth = value.Length - startlen - endlen;
            string str1 = value.Substring(startlen, lenth);
            string str2 = string.Empty;
            for (int i = 0; i < str1.Length; i++)
            {
                str2 += StarChar;
            }
            label1.Text = value.Replace(str1, str2);
        }

        public static readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)   //是否显示账号
        {
            if (checkBox1.Checked)
            {
                label1.Text = Form1.username;
            }
            else
            {
                ShowUser(Form1.username);   //调用方法显示*号
            }
        }

        private void CheckBox2_CheckedChanged(object sender, EventArgs e)       //是否显示身份证号
        {
            SqlConnection con = new SqlConnection(Stu);
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandText = "select Name,IDcard from 实名信息表 where username='" + Form1.username + "'";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                if (checkBox2.Checked)
                {
                    textBox2.Text = reader.GetString(reader.GetOrdinal("Name"));
                    ShowIDcard(Form1.username);  //调用方法函数,显示完整身份证号
                }
                else
                {
                    HideDcard(Form1.username);  //显示加密后的身份证号
                }
            }
            con.Close();
        }

        public  void ShowIDcard(string text)  //显示完整的实名信息
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select Name,IDcard from 实名信息表 where username='" + text + "'";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read() )
            {
                textBox3.Text = reader.GetString(reader.GetOrdinal("IDcard"));
            }
            conn.Close();
        }

        public void HideDcard(string text)  //用'*'号加密身份证号
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select Name,IDcard from 实名信息表 where username='" + text + "'";
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
            {
                string sdd = "*";
                string IDcard = reader.GetString(reader.GetOrdinal("IDcard"));
                for (int i = 0; i < IDcard.Length - 3; i++)
                {
                    sdd += "*";
                }
                textBox3.Text = IDcard.Substring(0, 1) + sdd + IDcard.Substring(IDcard.Length - 2, 2);
            }
            else
            {
                textBox3.Text = "";
            }
            conn.Close();
        }

        private void Form3_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }

        protected override void OnClosing(CancelEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}




窗体Form3界面效果截图

Form3




4、窗体Form4:修改密码界面


label2——旧密码,label3——新密码

textBox2(对应旧密码),textBox3(对应新密码)

Button1——确认,Button2——重置,Button3——取消


窗体Form4的控件布局

Form4控件布局


窗体Form4的源代码

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace CT12
{
    public partial class Form4 : Form
    {
        public Form4()
        {
            InitializeComponent();
            this.Text = "修改密码";
            ScreenSize();
        }

      private void ScreenSize()
        {
            int x = Screen.GetBounds(this).Width;
            int y = Screen.GetBounds(this).Height;
            this.MinimumSize = new Size(x / 2, y / 2);
            this.MaximumSize = new Size(x / 2, y / 2);
            this.CenterToParent();
            this.CenterToScreen();
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            ScreenSize();
            textBox2.PasswordChar = '*';
            textBox3.PasswordChar = '*';
            this.ActiveControl = textBox2;
        }

        private void Button3_Click(object sender, EventArgs e)  //返回窗体Form3:主界面
        {
            this.Hide();
            Form3 df = new Form3();
            df.Show();
        }

        private void Button2_Click(object sender, EventArgs e)  //重置textBox文本框的输入信息
        {
            this.ActiveControl = textBox2;
            textBox2.Text = "";
            textBox3.Text = "";
        }

        private readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;  //创建数据库连接

        private void Button1_Click(object sender, EventArgs e)
        {
            Encrypt1 SHA256 = new Encrypt1();
            string oldPassword = textBox2.Text.Trim();//旧密码
            string newPassword = textBox3.Text.Trim();//新密码
            using (SqlConnection conn = new SqlConnection(Stu))
            {
                conn.Open();
                string sql = "SELECT password FROM 登录注册表 WHERE username=@username";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddWithValue("@username", Form1.username);
                    object result = cmd.ExecuteScalar();
                    // 判断密码是否正确
                    if (result != null && result.ToString() == SHA256.EncryptPassword(Form1.username + oldPassword))
                    {
                        // 判断新旧密码是否相同
                        if (oldPassword != newPassword)
                        {
                            // 更新密码
                            sql = "update 登录注册表 set password=@password WHERE username=@username";
                            using (SqlCommand updateCmd = new SqlCommand(sql, conn))
                            {
                                updateCmd.Parameters.AddWithValue("@password", SHA256.EncryptPassword(Form1.username + newPassword));
                                updateCmd.Parameters.AddWithValue("@username", Form1.username);
                                int rowsAffected = updateCmd.ExecuteNonQuery();
                                // 提示密码修改成功
                                MessageBox.Show("账号密码修改成功!请重新登录!");
                                this.Hide();
                                Form1 sd = new Form1();
                                sd.Show();
                                conn.Close();
                            }
                        }
                        else
                        {
                            MessageBox.Show("新旧密码不得相同!");
                            textBox2.Text = "";
                            textBox3.Text = "";
                            this.ActiveControl = textBox2;
                        }
                    }
                    else
                    {
                        MessageBox.Show("账号密码错误!");
                        textBox2.Text = "";
                        textBox3.Text = "";
                        this.ActiveControl = textBox2;
                    }
                }
            }
        }

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)   //textBox2文本框输入是否显示为"*"
        {
            if (checkBox1.Checked)
            {
                textBox2.PasswordChar = '\0';
            }
            else
            {
                textBox2.PasswordChar = '*';
            }
        }

        private void CheckBox2_CheckedChanged(object sender, EventArgs e)   // //textBox3文本框输入是否显示为"*"
        {
            if (checkBox1.Checked)
            {
                textBox3.PasswordChar = '\0';
            }
            else
            {
                textBox3.PasswordChar = '*';
            }
        }

        private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}



窗体Form4运行效果截图

在这里插入图片描述


在这里插入图片描述




5、窗体Form5:账号注销界面


label2——账号密码,textBox2——对应当前账号密码,

button1——注销,button2——重置,button3——取消


窗体Form5的控件布局

控件布局


窗体Form5的源代码

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace CT12
{
    public partial class Form5 : Form
    {
        public Form5()
        {
            InitializeComponent();
            this.Text = "账号注销";
            ScreenSize();
        }

        public void ScreenSize()
        {
            int x = Screen.GetBounds(this).Width;
            int y = Screen.GetBounds(this).Height;
            this.MinimumSize = new Size(x / 2, y / 2);
            this.MaximumSize = new Size(x / 2, y / 2);
            this.CenterToParent();
            this.CenterToScreen();
        }

        private void Form5_Load(object sender, EventArgs e)
        {
            ScreenSize();
            this.ActiveControl = textBox2;
        }

        private void Button3_Click(object sender, EventArgs e)  //返回窗体Form3:主界面
        {
            this.Hide();
            Form3 sd = new Form3();
            sd.Show();
        }

        private void Button2_Click(object sender, EventArgs e)  //重置textBox文本框的信息
        {
            textBox2.Text = "";
            this.ActiveControl = textBox2;
        }

        private readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;

        private void Button1_Click(object sender, EventArgs e)  //账号注销功能
        {
            Encrypt1 SHA256 = new Encrypt1();
            using (SqlConnection conn = new SqlConnection(Stu))
            {
                conn.Open();
                SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM 登录注册表 WHERE username=@username AND password=@password", conn);
                command.Parameters.AddWithValue("@username", Form1.username); // 账号使用 Form1 中的 username
                command.Parameters.AddWithValue("@password", SHA256.EncryptPassword(Form1.username+textBox2.Text));
                int count = (int)command.ExecuteScalar();
                if (count == 1) // 如果存在该账号且密码正确
                {
                    try
                    {
                        // 构建 SQL 删除语句,删除该账号和密码
                        SqlCommand deleteCommand = new SqlCommand("DELETE FROM 登录注册表 WHERE username=@username AND password=@password", conn);
                        deleteCommand.Parameters.AddWithValue("@username", Form1.username); // 使用 form1 中的 username
                        deleteCommand.Parameters.AddWithValue("@password", SHA256.EncryptPassword(Form1.username+textBox2.Text));
                        deleteCommand.ExecuteNonQuery();
                        MessageBox.Show("账号注销成功!");
                        Delete2();//同时删除实名信息的数据
                        this.Hide();
                        Form1 sd = new Form1();
                        sd.Show();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("账号注销失败!" + ex.Message);
                    }
                
                }
                else
                {
                    MessageBox.Show("账号密码错误!");
                    textBox2.Text = "";
                    this.ActiveControl = textBox2;
                }
            }
        }

       private void Delete2()      //删除注销账号的实名信息
        {
            using (SqlConnection conn = new SqlConnection(Stu))
            {
                conn.Open();
                try
                {
                    // 构建 SQL 删除语句,删除该账号和密码
                    SqlCommand deleteCommand = new SqlCommand("delete from 实名信息表 where username=@username", conn);
                    deleteCommand.Parameters.AddWithValue("@username", Form1.username); // 使用 form1 中的 username
                    deleteCommand.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("账号注销失败!" + ex.Message);
                }
                conn.Close();
            }
        }

        private void Form5_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}




6、窗体Form6:实名认证界面


label1——姓名,label2——身份证号

textBox1——对应姓名,textBox2——对应身份证号

button1——绑定,button2——重置,button3——返回


窗体Form6的控件布局

Form6控件布局


窗体Form6源代码

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;

namespace CT12
{
    public partial class Form6 : Form
    {
        public Form6()
        {
            InitializeComponent();
            this.Text = "实名认证";
            ScreenSize();
        }

        private void Form6_Load(object sender, EventArgs e)
        {
            ScreenSize();
        }

        public void ScreenSize()
        {
            int x = Screen.GetBounds(this).Width;
            int y = Screen.GetBounds(this).Height;
            this.MinimumSize = new Size(x / 2, y / 2);
            this.MaximumSize = new Size(x / 2, y / 2);
            this.CenterToParent();
            this.CenterToScreen();
        }
        private void Button3_Click(object sender, EventArgs e)
        {
            this.Hide();
            Form3 sd = new Form3();
            sd.Show();
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            textBox2.Text = "";
        }

        public string MD5Encrypt(string rawPass, string salt)      //MD5加盐加密
        {
            MD5 md5 = MD5.Create();
            byte[] bs = Encoding.UTF8.GetBytes(rawPass + salt);
            byte[] ts = md5.ComputeHash(bs);
            StringBuilder std = new StringBuilder();
            foreach (byte i in ts)
            {
                std.Append(i.ToString("x2"));
            }
            return std.ToString();  //返回密文
        }

       public static readonly string Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;

        public static string name;  //创建参数name,实名认证成功后显示在主界面Form3
        public static string IDcard;    //创建参数IDcard,实名认证成功后显示在主界面Form3

        private void Button1_Click(object sender, EventArgs e)      //绑定操作
        {
            SqlConnection conn = new SqlConnection(Stu);
            conn.Open();
            // 查询该账号是否已经实名认证过
            string sqlQuery = $"SELECT COUNT(*) FROM 实名信息表 WHERE username='{Form1.username}'";
            SqlCommand cmdQuery = new SqlCommand(sqlQuery, conn);
            int count = (int)cmdQuery.ExecuteScalar();
            if (count > 0)
            {
                MessageBox.Show("该账号已实名认证");
            }
            else
            {
                // 查询该身份证号是否已被其他人注册
                string sqlCheckID = $"SELECT COUNT(*) FROM 实名信息表 WHERE IDcard='{textBox2.Text.Trim()}'";
                SqlCommand cmdCheckID = new SqlCommand(sqlCheckID, conn);
                int idCount = (int)cmdCheckID.ExecuteScalar();
                if (idCount > 0)
                {
                    MessageBox.Show("该身份证已经被别人注册");
                }
                else
                {
                    try
                    {
                        // 绑定实名认证账号
                        string sqlInsert = $"INSERT INTO 实名信息表 (username, Name, IDcard) VALUES ('{Form1.username}', '{textBox1.Text.Trim()}', '{textBox2.Text.Trim()}')";
                        SqlCommand cmdInsert = new SqlCommand(sqlInsert, conn);
                        cmdInsert.ExecuteNonQuery();
                        conn.Close();
                        MessageBox.Show("实名认证成功!");
                        this.Hide();
                        Form1 sd = new Form1();
                        sd.Show();
                    }
                    catch(Exception ex)
                    {
                        MessageBox.Show("实名认证失败!" + ex.Message);
                    }
                }
            }
            conn.Close(); // 关闭数据库连接
        }

        private void Form6_FormClosing(object sender, FormClosingEventArgs e)
        {
            Process.GetCurrentProcess().Kill();
        }
    }
}





Form6运行效果截图

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述




总结


以上就是今天要跟大家分享的内容,可能代码有点多,代码逻辑看起来比较乱,花了几个星期时间写的,期间修修改改了很多次,尚且还有不足之处,仅供学习和参考;感兴趣的小伙伴可以来看看,希望对你有所帮助,也欢迎大家的批评指正。


本人声明:未经本人许可,禁止转载!!!如果要引用部分代码,请标明出处!!



版权声明:本文为qq_60423778原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。