Authors
: Nie BaoGen
登陆界面实现
后台代码实现
//获取用户输入信息
string uName = txtUserId.Text.Trim();
string uPwd = txtUserPwd.Text.Trim();
//判断是否为空,值为空或者空字符串
if (string.IsNullOrEmpty(uName))
{
//设置提示框的标题和提示信息,消息提示框的图标
MessageBox.Show("账户为空,请重新输入!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserId.Focus();//焦点定位
return;
}
if (string.IsNullOrEmpty(uPwd))
{
MessageBox.Show("密码为空,请重新输入!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserPwd.Focus();
return;
}
//与数据库通信,检查输入与数据库中是否一致
//建立与数据库的连接
//连接字符串,---钥匙
string connString = "data source=localhost;database=studentdb;user id=root;password=admin;charset=utf8";
MySqlConnection conn = new MySqlConnection(connString);
//写查询语句
string sql="select count(1) from UserInfo where UserID='"+uName+"' and UserPwd='"+uPwd+"'";
//创建Command对象
MySqlCommand mySqlCommand = new MySqlCommand(sql, conn);//sql语句和连接对象
conn.Open();//最晚打开,最早关闭
//执行命令(要求必须在连接状态),并返回结果集第一行第一列的值,忽略其他行或列
object o = mySqlCommand.ExecuteScalar();
//执行存储过程
//mySqlCommand.CommandType = CommandType.StoredProcedure;
//关闭连接
conn.Close();
//处理结果
//根据返回的结果给出不同的提示
if (o == null || o == DBNull.Value || Convert.ToInt32(o)==0)
{
MessageBox.Show("账号或密码有错,请检查", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("登陆成功", "成功提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
//执行命令
//关闭连接
//处理结果
}
private void btn_Exit_Click(object sender, EventArgs e)
{
this.Close();//关闭启动窗口所在页面
//Application.Exit();//关闭本窗口
//Application.ExitThread();//提示是否关闭
}
}
我用的是Mysql数据库,所以需要引入Mysql的命名空间
using MySql.Data.MySqlClient;
具体步骤
获取用户输入数据:
//获取用户输入信息
string uName = txtUserId.Text.Trim();
//判断是否为空,值为空或者空字符串
if (string.IsNullOrEmpty(uName))
{
//设置提示框的标题和提示信息,消息提示框的图标
MessageBox.Show("账户为空,请重新输入!", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtUserId.Focus();//焦点定位
return;
}
//建立与数据库的连接
//连接字符串,---钥匙
string connString = "data source=localhost;database=studentdb;user id=root;password=admin;charset=utf8";
MySqlConnection conn = new MySqlConnection(connString);
//写查询语句
string sql="select count(1) from UserInfo where UserID='"+uName+"' and UserPwd='"+uPwd+"'";
//创建Command对象
MySqlCommand mySqlCommand = new MySqlCommand(sql, conn);//sql语句和连接对象
conn.Open();//最晚打开,最早关闭
//执行命令(要求必须在连接状态),并返回结果集第一行第一列的值,忽略其他行或列
object o = mySqlCommand.ExecuteScalar();
//执行存储过程
//mySqlCommand.CommandType = CommandType.StoredProcedure;
//关闭连接
conn.Close();
//处理结果
if (o == null || o == DBNull.Value || Convert.ToInt32(o)==0)
{
MessageBox.Show("账号或密码有错,请检查", "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}