输入正确账号密码时返回的count为1,输入错误账号密码时,不执行else,接收不到count的值
public void button1_Click(object sender, EventArgs e)
{
string name = this.nameBox.Text.Trim();
string password = this.pwdBox.Text.Trim();
if (name == string.Empty || password == string.Empty)
{
MessageBox.Show("你的学号或密码为空!");
return;
}
MySqlConnectionStringBuilder buider = new MySqlConnectionStringBuilder();
//用户名
buider.UserID = "root";
//密码
buider.Password = "123456";
//服务器地址
buider.Server = "localhost";
//端口号
buider.Port = 3306;
//连接时的数据库
buider.Database = "studentGrade";
//定义数据库的连接
MySqlConnection conn = new MySqlConnection(buider.ConnectionString);
//打开数据库连接
conn.Open();
//定义语句
string sql = String.Format("select * from tb_user where username = '{0}' and password = '{1}' " ,name,password);
MySqlCommand command = new MySqlCommand(sql, conn);
int count = (int)(command.ExecuteScalar());//Convert.ToInt64,Convert.ToInt32
//检查用户名是否正确
MessageBox.Show("他的值" + count);
if (count > 0)
{
MessageBox.Show("登陆成功!");
Form1 f1 = new Form1(name);
this.Hide();
f1.Show();
}
else
{
MessageBox.Show("学号或密码错误,请重新输入你的学号或密码!");
this.textBox1.Clear();
this.pwdBox.Clear();
this.textBox1.Focus();
}
}
代码,请勿粘贴截图
强转类型
正确密码是顺利跳转到另一个界面
密码错误是产生提示
SQL 语句 改成
string sql = String.Format("select count(1) from tb_user where username = '{0}' and password = '{1}' " ,name,password);
ExecuteScalar 获取的是第一行第一列的值 账号密码不对的话就是null 强制转换就会报错
不改SQL语句的 方案就是 判断一下执行结果 如果是空 把count赋值为0也行。
ExecuteScalar返回的是对象,所以一般判断它,用对象就可以了
object obj=command.ExecuteScalar();
if(obj!=null)
{
}
else
{
}