c#实现登录,注册功能
登录界面:
主窗体为登录界面,输入用户名和密码,单击“登录”按钮时从数据库中读取数据,与输入的用户名、密码验证,验证通过后,登录窗体消失。单击“注册”按钮时窗体中的输入的数据保存到数据库中 。
代码实现:
private void button1_Click(object sender, EventArgs e)
{
//获取界面上用户输入信息
string userName = textBox1.Text;
string userPwd = textBox2.Text;
//2.运用Connection对象建立与数据库的连接
//(1)定义连接数据库的字符串
string connStr = "server=DESKTOP-XXXX;database=数据库名;uid=账号;pwd=密码";//采用混合身份验证
//(2)创建Connection对象
SqlConnection conn = new SqlConnection(connStr);
//(3)打开连接
conn.Open();
//3.利用Command对象执行sql语句
//(1)定义要执行的sql语句
string sql = "select count(1) from 数据表 where userName=@t1 and userPwd=@t2 ";
//(2)通过Connection对象和sql语句,创建Command对象
SqlCommand cmd = new SqlCommand(sql, conn);
//(3)处理Command对象的参数
cmd.Parameters.Add("@t1", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("@t2", SqlDbType.VarChar).Value = userPwd;
//(4)执行SQL语句
if ((int)cmd.ExecuteScalar() > 0)
{
Form2 Form2 = new Form2();
userName = textBox1.Text;
userPwd = textBox2.Text;
Form2.Show();//登录成功显示的下一个页面
MessageBox.Show("欢迎进入!", "登陆成功!", MessageBoxButtons.OK, MessageBoxIcon.Information);
// this.Hide(); //查到数据的处理逻辑代码
}
else
{
//没查到数据的处理逻辑代码
MessageBox.Show("用户名或者密码错误", "!提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//4.关闭数据库连接
conn.Close();
}
数据库设计
注册功能
注册功能会判断数据库是否存在用户,如果注册成功会将账号和密码存储进数据库。
注意:账号具有唯一性,在数据库中需要将账号字段设置为唯一键。
注册界面:
代码实现:
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("用户名不能为空!");
}
if (textBox2.Text == "")
{
MessageBox.Show("密码不能为空!");
}
if (textBox3.Text == "")
{
MessageBox.Show("确认密码不能为空!");
}
if (textBox2.Text != textBox3.Text)
{
MessageBox.Show("密码和确认密码不相符!");
textBox2.Text = "";
textBox3.Text = "";
}
try
{
string sql = string.Format("select count(*) from 数据库 where userName='{0}'", textBox1.Text);
SqlCommand cmd = new SqlCommand(sql, MyMeans.conn);
MyMeans.conn.Open();
int a = (int)cmd.ExecuteScalar();//返回一个值,看用户是否存在
StringBuilder strsql = new StringBuilder();
if (a == 0)
{
strsql.Append("insert into 数据表(userName,userPwd)");
strsql.Append("values(");
strsql.Append("'" + textBox1.Text.Trim().ToString() + "',");
strsql.Append("'" + textBox2.Text.Trim().ToString() + "'");
strsql.Append(")");
using (SqlCommand cmd2 = new SqlCommand(strsql.ToString(), MyMeans.conn))
{
cmd2.ExecuteNonQuery();
}
MessageBox.Show("注册成功!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Close();
}
else
{
MessageBox.Show("用户已存在!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
this.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
Application.Exit();
}
finally
{
MyMeans.conn.Close();
MyMeans.conn.Dispose();
}
}
新手小白,第一次编写。
还有不足,多谢指导。