麻烦大神们看看这段代码是不是缺少什么还是有问题,为什么我每次登陆的时候显示的都是“操作数据库出错”
namespace MySchool
{
/// <summary>
/// 登录窗体
/// </summary>
public partial class LoginForm : Form
{
public LoginForm()
{
InitializeComponent();
}
// “登录”按钮的单击事件
private void btnLogin_Click(object sender, EventArgs e)
{
bool isValidUser = false; // 标识是否为合法用户
string message = "";
if (ValidateInput()) // 验证输入成功,显示窗体
{
// 验证用户是否为合法用户
isValidUser = ValidateUser(
txtLoginId.Text,
txtLoginPwd.Text,
cboLoginType.Text,
ref message
);
// 如果是合法用户,就转到相应的窗体
if (isValidUser)
{
// 记录登录用户名和登录类型
UserHelper.loginId = txtLoginId.Text;
UserHelper.loginType = cboLoginType.Text;
switch (cboLoginType.Text)
{
case "学员":
// 试题选择窗体对象
StudentForm studentForm = new StudentForm();
studentForm.loginForm = this;
// 显示窗体
studentForm.Show();
break;
default:
MessageBox.Show("抱歉,功能尚未开通!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);
break;
}
// 登录窗体隐藏
this.Visible = false;
}
else // 验证合法用户失败,给出提示
{
MessageBox.Show(message,"登录提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
}
}
// 验证用户的输入
// 成功返回 True,失败返回 False
private bool ValidateInput()
{
if (txtLoginId.Text.Trim() == "")
{
MessageBox.Show("请输入用户名", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtLoginId.Focus();
return false;
}
else if (txtLoginPwd.Text.Trim() == "")
{
MessageBox.Show("请输入密码", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
txtLoginPwd.Focus();
return false;
}
else if (cboLoginType.Text.Trim() == "")
{
MessageBox.Show("请选择登录类型", "登录提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
cboLoginType.Focus();
return false;
}
else
{
return true;
}
}
// 验证用户是否合法
// 传入用户名、密码、登录类型
// 合法返回 True,不合法返回 False
// message 参数用来记录验证失败的原因
private bool ValidateUser(string loginId, string loginPwd, string loginType, ref string message)
{
string tableName = ""; // 要查询的数据表的名称
bool result = true; // 返回值
// 根据登录类型,确定数据表名称
switch (loginType)
{
case "教员":
tableName = "Teacher";
break;
case "学员":
tableName = "Student";
break;
case "管理员":
tableName = "Admin";
break;
default:
message = "登录类型错误!";
result = false;
break;
}
// 查询字符串
string sql = string.Format(
"SELECT COUNT(*) FROM {0} WHERE LoginId='{1}' AND LoginPwd='{2}'",
tableName,loginId, loginPwd);
try
{
// 创建 Command 对象
SqlCommand command = new SqlCommand(sql, DBHelper.connection);
// 打开数据库连接
DBHelper.connection.Open();
// 验证是否为合法用户
int count = (int)command.ExecuteScalar();
if (count < 1)
{
message = "用户名或密码不存在!";
result = false;
}
else
{
result = true;
}
}
catch (Exception ex)
{
message = "操作数据库出错!";
Console.WriteLine(ex.Message);
result = false;
}
finally
{
// 关闭数据库连接
DBHelper.connection.Close();
}
return result;
}
// 退出登录
private void btnCancel_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
}
}
------解决思路----------------------
如果你按我说的改了,传入的参数数量也要改成2个啊,密码就别传进去了