logo资料库

C#中用户注册和登录的实现.docx

第1页 / 共6页
第2页 / 共6页
第3页 / 共6页
第4页 / 共6页
第5页 / 共6页
第6页 / 共6页
资料共6页,全文预览结束
1 数据库部分 我是采用的是 Mysql 数据库做的。 1.1 建数据库 Create database blog; 说明:blog 为数据库名称 1.2 建表 表的名称为 Users,包含以下属性: IdUser(用户编码),UsersName(用户名),UserPwd (用户密码)。 1.3 添加几条数据 上图中的 1~10 即是我插入的数据,可以引用 SQL 命令: Insert into users values( 1,’admin’,’admin’; 2,’lzugis’,’lzugis’; …… ) 2、C#部分 2.1 界面 做的界面很简单、丑陋。
最主要的:四个 label,两个 button 和两个 textbox;有两个标签是即时显示状态的。 2.2 添加用户的实现 #region 新注册用户 privatevoidRigster() { MySQLConnectionconn=null; conn=newMySQLConnection(newMySQLConnectionString(server: "localhost",database:"Blog",login:"root",pass:"admin",port:3306).AsString); stringsql1="SELECTUsersNameFROMusers"; MySQLDataAdapterAdpt=newMySQLDataAdapter(sql1,conn); DataTableDT=newDataTable(); Adpt.Fill(DT); intl=DT.Rows.Count; //l记录数据库中的条数 conn.Open(); stringname,pwd,sql2; name=textBox1.Text; pwd=textBox2.Text; l=l+1; sql2="INSERTINTOusers(`idUsers`,`Usersname`,`UserPwd`)VALUES ("+l+",'"+name+"','"+pwd+"')"; MySQLCommandcmd=newMySQLCommand(sql2,conn); try{ cmd.ExecuteNonQuery(); MessageBox.Show("注册成功!"); label3.Text=""; label4.Text=""; textBox1.Clear(); textBox2.Clear(); }catch(System.ExceptionE) { MessageBox.Show(E.ToString()); }
finally { cmd.Dispose(); } }privatevoidbutton3_Click(objectsender,EventArgse) { if(textBox1.Text=="") { label3.Text="用户名不能为空!"; textBox1.Focus(); }elseif(label3.Text=="right") { MessageBox.Show("用户名已注册!"); textBox1.Clear(); textBox2.Clear(); label3.Text=""; label4.Text=""; textBox1.Focus(); }elseif(textBox2.Text=="") { label4.Text="密码不能为空!"; textBox2.Focus(); }else{ Rigster(); } }#endregion #region 判断用户是否存在 privatevoidJudgeName() { MySQLConnectionconn=null; conn=newMySQLConnection(newMySQLConnectionString(server: "localhost",database:"Blog",login:"root",pass:"admin",port:3306).AsString); stringsql="SELECTUsersNameFROMusers"; 2.3 用户登录的实现 2.3.1 判断用户名是否存在
MySQLDataAdapterAdpt=newMySQLDataAdapter(sql,conn); DataTableDT=newDataTable(); Adpt.Fill(DT); inti; for(i=0;i
+"'"; MySQLCommandcmd=newMySQLCommand(sql,conn); MySQLDataReaderRead=cmd.ExecuteReaderEx(); while(Read.Read()) { pwd=Read[0].ToString(); if(pwd==textBox2.Text) { label4.ForeColor=Color.Lime; label4.Text="正确"; }else{ label4.ForeColor=Color.Gray; label4.Text="密码不正确!"; } }conn.Close(); }privatevoidtextBox2_TextChanged(objectsender,EventArgse) { if(textBox2.Text=="") { label4.Text="密码不能为空!"; }else{ JudgePwd(); } }#endregion #region 用户登录 privatevoidbutton2_Click(objectsender,EventArgse) { if(label3.Text=="用户名存在"&&label4.Text=="正确") { MessageBox.Show("登陆成功!"); this.Close(); }else{ 2.3.3 登陆
label3.ForeColor=Color.Gray; textBox1.Text=""; textBox2.Text=""; label3.Text=""; label4.Text=""; textBox1.Focus(); } }#endregion
分享到:
收藏