0


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

目录

这是本人用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,在这些窗体中都会调用到。

usingSystem;usingSystem.Security.Cryptography;usingSystem.Text;namespaceCT12{classEncrypt1{publicstringEncryptPassword(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源代码

usingSystem;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Windows.Forms;usingSystem.Drawing;usingSystem.ComponentModel;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Diagnostics;namespaceCT12{publicpartialclassForm1:Form{publicForm1(){InitializeComponent();this.Text ="账号登录";ScreenSize();
            textBox2.PasswordChar ='*';//密码显示为"*"}publicvoidScreenSize()//设置窗体样式和居中显示{int x = Screen.GetBounds(this).Width;int y = Screen.GetBounds(this).Height;this.MinimumSize =newSize(x /2, y /2);this.MaximumSize =newSize(x /2, y /2);this.CenterToParent();this.CenterToScreen();}privatevoidForm1_Load(object sender,EventArgs e){ScreenSize();//调用函数this.ActiveControl = textBox1;//焦点在控件textBox1上面}privatevoidButton4_Click(object sender,EventArgs e)//跳转注册界面{this.Hide();Form2 sd =newForm2();
            sd.Show();}privatevoidButton2_Click(object sender,EventArgs e)//重置登录信息{
            textBox1.Text ="";
            textBox2.Text ="";this.ActiveControl = textBox1;}privatevoidbutton3_Click(object sender,EventArgs e)//强制退出窗体程序{
            Process.GetCurrentProcess().Kill();}privatestaticreadonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;//创建数据库连接publicstaticstring username;//设置Form1的一个参数,登录成功后将显示在主界面Form3publicstaticstring password;privatevoidButton1_Click(object sender,EventArgs e)//登录代码{Encrypt1 SHA256 =newEncrypt1();//调用该加密类if(textBox1.Text.Equals("")){
                MessageBox.Show("账号不得为空!","提示");this.ActiveControl = textBox1;}elseif(textBox2.Text.Equals("")){
                MessageBox.Show("密码不得为空!","提示");this.ActiveControl = textBox2;}else{using(SqlConnection conn =newSqlConnection(Stu)){
                    conn.Open();string sql ="select count(*) from 登录注册表 where username=@username";SqlCommand cmd =newSqlCommand(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 =newForm2();
                            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 =newSqlCommand(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 =newForm3();
                    sd.Show();//显示主界面Form3}}}privatevoidCheckBox1_CheckedChanged(object sender,EventArgs e)//是否显示密码输入为“*”{if(checkBox1.Checked){
                textBox2.PasswordChar ='\0';}else{
                textBox2.PasswordChar ='*';}}protectedoverridevoidOnClosing(CancelEventArgs e){
            Process.GetCurrentProcess().Kill();}privatevoidForm1_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

窗体Form1运行效果截图

账号登录成功


在这里插入图片描述


在这里插入图片描述


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

label1——新用户名,label2——用户密码,label3——确认密码
textBox1(对应新用户名),textBox2(对应用户密码),textBox3(对应确认密码)
button1——确认,button2——重置,button3——返回

窗体Form2的控件布局

在这里插入图片描述

窗体Form2源代码

usingSystem;usingSystem.ComponentModel;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Windows.Forms;namespaceCT12{publicpartialclassForm2:Form{publicForm2(){InitializeComponent();this.Text ="账号注册";ScreenSize();}privatevoidForm2_Load(object sender,EventArgs e){ScreenSize();
            textBox2.PasswordChar ='*';//textBox2——用户密码显示为"*"
            textBox3.PasswordChar ='*';//textBox3——确认密码显示为"*"this.ActiveControl = textBox1;//焦点在输入框textBox1上}privatevoidScreenSize()//设置窗体大小尺寸和居中显示{int x = Screen.GetBounds(this).Width;//获取屏幕宽度int y = Screen.GetBounds(this).Height;//获取屏幕高度this.MinimumSize =newSize(x /2, y /2);//设置窗口最小尺寸this.MaximumSize =newSize(x /2, y /2);//设置窗口最大尺寸this.CenterToParent();this.CenterToScreen();}privatevoidButton2_Click(object sender,EventArgs e)//重置输入框信息{
            textBox1.Text ="";
            textBox2.Text ="";
            textBox3.Text ="";this.ActiveControl = textBox1;}privatevoidButton3_Click(object sender,EventArgs e)//返回登录界面Form1{this.Hide();Form1 sd =newForm1();
            sd.Show();}readonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;privatevoidButton1_Click(object sender,EventArgs e){Encrypt1 SHA256 =newEncrypt1();if(textBox1.Text.Equals("")){
                MessageBox.Show("注册账号不得为空!","提示");}elseif(textBox2.Text.Equals("")){
                MessageBox.Show("注册账号密码不得为空!","提示");}elseif(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 =newSqlConnection(Stu)){
                    conn.Open();SqlCommand command =newSqlCommand{
                        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 =newSqlConnection(Stu)){try{
                        connection.Open();SqlCommand command =newSqlCommand{
                            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 =newForm1();
                        sd.Show();}catch(Exception ex){
                        MessageBox.Show(ex.Message);}}}}privatevoidCheckBox1_CheckedChanged(object sender,EventArgs e)//textBox2文本框输入显示为"*"{if(checkBox1.Checked)
                textBox2.PasswordChar ='\0';else
                textBox2.PasswordChar ='*';}privatevoidCheckBox2_CheckedChanged(object sender,EventArgs e)//textBox3文本框输入为"*"{if(checkBox2.Checked)
                textBox3.PasswordChar ='\0';else
                textBox3.PasswordChar ='*';}protectedoverridevoidOnClosing(CancelEventArgs e){
            Process.GetCurrentProcess().Kill();}privatevoidForm2_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

窗体Form2运行效果截图

账号注册成功


账号已注册


3、窗体Form3:主界面

checkBox1——当前账号,Label1——显示账号
textBox1——显示姓名,textBox2——显示身份证号
Button1——修改密码,Button2——注销账号,Button5——实名认证,
Button3——返回,Button4——退出

窗体Form3的控件布局

在这里插入图片描述

窗体Form3的源代码

usingSystem;usingSystem.ComponentModel;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Windows.Forms;namespaceCT12{publicpartialclassForm3:Form{publicForm3(){InitializeComponent();this.Text ="账号信息";ScreenSize();}publicvoidScreenSize(){int x = Screen.GetBounds(this).Width;int y = Screen.GetBounds(this).Height;this.MinimumSize =newSize(x /2, y /2);this.MaximumSize =newSize(x /2, y /2);this.CenterToParent();this.CenterToScreen();}privatevoidForm3_Load(object sender,EventArgs e){ScreenSize();ShowUser(Form1.username);this.HideDcard(Form1.username);ShowName();}publicvoidShowName()//在主界面显示实名信息{using(SqlConnection conn =newSqlConnection(Stu)){// 打开连接
                conn.Open();// 查询该账户是否实名认证string query ="SELECT Name, IDcard FROM 实名信息表 WHERE username = @username ";using(SqlCommand command =newSqlCommand(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();}}}privatevoidButton1_Click(object sender,EventArgs e)//跳转窗体Form4:修改密码界面{this.Hide();Form4 df =newForm4();
            df.Show();}privatevoidButton2_Click(object sender,EventArgs e)//跳转窗体Form5:注销账号界面{this.Hide();Form5 sd =newForm5();
            sd.Show();}privatevoidButton4_Click(object sender,EventArgs e)//强制退出所有窗口程序和线程{
            Process.GetCurrentProcess().Kill();}privatevoidButton3_Click(object sender,EventArgs e)//返回窗体Form1:登录界面{DialogResult dr = MessageBox.Show("是否返回登录界面?","提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information);if(dr == DialogResult.Yes){this.Hide();Form1 sdd =newForm1();
                sdd.Show();}}privatevoidButton5_Click_1(object sender,EventArgs e){this.Hide();Form6 asd =newForm6();
            asd.Show();}publicvoidShowUser(string text){char StarChar ='*';stringvalue= 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);}publicstaticreadonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;privatevoidCheckBox1_CheckedChanged(object sender,EventArgs e)//是否显示账号{if(checkBox1.Checked){
                label1.Text = Form1.username;}else{ShowUser(Form1.username);//调用方法显示*号}}privatevoidCheckBox2_CheckedChanged(object sender,EventArgs e)//是否显示身份证号{SqlConnection con =newSqlConnection(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();}publicvoidShowIDcard(string text)//显示完整的实名信息{SqlConnection conn =newSqlConnection(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();}publicvoidHideDcard(string text)//用'*'号加密身份证号{SqlConnection conn =newSqlConnection(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();}privatevoidForm3_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}protectedoverridevoidOnClosing(CancelEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

窗体Form3界面效果截图

Form3


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

label2——旧密码,label3——新密码
textBox2(对应旧密码),textBox3(对应新密码)
Button1——确认,Button2——重置,Button3——取消

窗体Form4的控件布局

Form4控件布局

窗体Form4的源代码

usingSystem;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Windows.Forms;namespaceCT12{publicpartialclassForm4:Form{publicForm4(){InitializeComponent();this.Text ="修改密码";ScreenSize();}privatevoidScreenSize(){int x = Screen.GetBounds(this).Width;int y = Screen.GetBounds(this).Height;this.MinimumSize =newSize(x /2, y /2);this.MaximumSize =newSize(x /2, y /2);this.CenterToParent();this.CenterToScreen();}privatevoidForm4_Load(object sender,EventArgs e){ScreenSize();
            textBox2.PasswordChar ='*';
            textBox3.PasswordChar ='*';this.ActiveControl = textBox2;}privatevoidButton3_Click(object sender,EventArgs e)//返回窗体Form3:主界面{this.Hide();Form3 df =newForm3();
            df.Show();}privatevoidButton2_Click(object sender,EventArgs e)//重置textBox文本框的输入信息{this.ActiveControl = textBox2;
            textBox2.Text ="";
            textBox3.Text ="";}privatereadonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;//创建数据库连接privatevoidButton1_Click(object sender,EventArgs e){Encrypt1 SHA256 =newEncrypt1();string oldPassword = textBox2.Text.Trim();//旧密码string newPassword = textBox3.Text.Trim();//新密码using(SqlConnection conn =newSqlConnection(Stu)){
                conn.Open();string sql ="SELECT password FROM 登录注册表 WHERE username=@username";using(SqlCommand cmd =newSqlCommand(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 =newSqlCommand(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 =newForm1();
                                sd.Show();
                                conn.Close();}}else{
                            MessageBox.Show("新旧密码不得相同!");
                            textBox2.Text ="";
                            textBox3.Text ="";this.ActiveControl = textBox2;}}else{
                        MessageBox.Show("账号密码错误!");
                        textBox2.Text ="";
                        textBox3.Text ="";this.ActiveControl = textBox2;}}}}privatevoidCheckBox1_CheckedChanged(object sender,EventArgs e)//textBox2文本框输入是否显示为"*"{if(checkBox1.Checked){
                textBox2.PasswordChar ='\0';}else{
                textBox2.PasswordChar ='*';}}privatevoidCheckBox2_CheckedChanged(object sender,EventArgs e)// //textBox3文本框输入是否显示为"*"{if(checkBox1.Checked){
                textBox3.PasswordChar ='\0';}else{
                textBox3.PasswordChar ='*';}}privatevoidForm4_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

窗体Form4运行效果截图

在这里插入图片描述


在这里插入图片描述


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

label2——账号密码,textBox2——对应当前账号密码,
button1——注销,button2——重置,button3——取消

窗体Form5的控件布局

控件布局

窗体Form5的源代码

usingSystem;usingSystem.Configuration;usingSystem.Data.SqlClient;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Windows.Forms;namespaceCT12{publicpartialclassForm5:Form{publicForm5(){InitializeComponent();this.Text ="账号注销";ScreenSize();}publicvoidScreenSize(){int x = Screen.GetBounds(this).Width;int y = Screen.GetBounds(this).Height;this.MinimumSize =newSize(x /2, y /2);this.MaximumSize =newSize(x /2, y /2);this.CenterToParent();this.CenterToScreen();}privatevoidForm5_Load(object sender,EventArgs e){ScreenSize();this.ActiveControl = textBox2;}privatevoidButton3_Click(object sender,EventArgs e)//返回窗体Form3:主界面{this.Hide();Form3 sd =newForm3();
            sd.Show();}privatevoidButton2_Click(object sender,EventArgs e)//重置textBox文本框的信息{
            textBox2.Text ="";this.ActiveControl = textBox2;}privatereadonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;privatevoidButton1_Click(object sender,EventArgs e)//账号注销功能{Encrypt1 SHA256 =newEncrypt1();using(SqlConnection conn =newSqlConnection(Stu)){
                conn.Open();SqlCommand command =newSqlCommand("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 =newSqlCommand("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 =newForm1();
                        sd.Show();}catch(Exception ex){
                        MessageBox.Show("账号注销失败!"+ ex.Message);}}else{
                    MessageBox.Show("账号密码错误!");
                    textBox2.Text ="";this.ActiveControl = textBox2;}}}privatevoidDelete2()//删除注销账号的实名信息{using(SqlConnection conn =newSqlConnection(Stu)){
                conn.Open();try{// 构建 SQL 删除语句,删除该账号和密码SqlCommand deleteCommand =newSqlCommand("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();}}privatevoidForm5_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

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

label1——姓名,label2——身份证号
textBox1——对应姓名,textBox2——对应身份证号
button1——绑定,button2——重置,button3——返回

窗体Form6的控件布局

Form6控件布局

窗体Form6源代码

usingSystem;usingSystem.Configuration;usingSystem.Data;usingSystem.Data.SqlClient;usingSystem.Diagnostics;usingSystem.Drawing;usingSystem.Security.Cryptography;usingSystem.Text;usingSystem.Windows.Forms;usingstaticSystem.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;namespaceCT12{publicpartialclassForm6:Form{publicForm6(){InitializeComponent();this.Text ="实名认证";ScreenSize();}privatevoidForm6_Load(object sender,EventArgs e){ScreenSize();}publicvoidScreenSize(){int x = Screen.GetBounds(this).Width;int y = Screen.GetBounds(this).Height;this.MinimumSize =newSize(x /2, y /2);this.MaximumSize =newSize(x /2, y /2);this.CenterToParent();this.CenterToScreen();}privatevoidButton3_Click(object sender,EventArgs e){this.Hide();Form3 sd =newForm3();
            sd.Show();}privatevoidButton2_Click(object sender,EventArgs e){
            textBox1.Text ="";
            textBox2.Text ="";}publicstringMD5Encrypt(string rawPass,string salt)//MD5加盐加密{MD5 md5 = MD5.Create();byte[] bs = Encoding.UTF8.GetBytes(rawPass + salt);byte[] ts = md5.ComputeHash(bs);StringBuilder std =newStringBuilder();foreach(byte i in ts){
                std.Append(i.ToString("x2"));}return std.ToString();//返回密文}publicstaticreadonlystring Stu = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;publicstaticstring name;//创建参数name,实名认证成功后显示在主界面Form3publicstaticstring IDcard;//创建参数IDcard,实名认证成功后显示在主界面Form3privatevoidButton1_Click(object sender,EventArgs e)//绑定操作{SqlConnection conn =newSqlConnection(Stu);
            conn.Open();// 查询该账号是否已经实名认证过string sqlQuery =$"SELECT COUNT(*) FROM 实名信息表 WHERE username='{Form1.username}'";SqlCommand cmdQuery =newSqlCommand(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 =newSqlCommand(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 =newSqlCommand(sqlInsert, conn);
                        cmdInsert.ExecuteNonQuery();
                        conn.Close();
                        MessageBox.Show("实名认证成功!");this.Hide();Form1 sd =newForm1();
                        sd.Show();}catch(Exception ex){
                        MessageBox.Show("实名认证失败!"+ ex.Message);}}}
            conn.Close();// 关闭数据库连接}privatevoidForm6_FormClosing(object sender,FormClosingEventArgs e){
            Process.GetCurrentProcess().Kill();}}}

Form6运行效果截图

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述


总结

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

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

标签: c# 服务器 数据库

本文转载自: https://blog.csdn.net/qq_60423778/article/details/126300151
版权归原作者 书海shuhai 所有, 如有侵权,请联系我们删除。

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

还没有评论