小弟刚学C#,刚才做了一个登录窗口,输入用户名和密码就可以打开主系统窗口,
下面是点击<登录>按钮的代码,如果输入的用户名和密码正确能成功找开主系统窗口,
但是如果用户名或密码错误,会提示:
int count = int.Parse(myCmd.ExecuteScalar().ToString());这句话错误!哪位大侠帮我看看,谢谢了!
private void but_login_Click(object sender, EventArgs e)
{
string user = this.txt_name.Text;
string pass = this.txt_pass.Text;
string sql = "select * from j_adminuser where userid='"+user+"' and password='"+pass+"'";
try
{
SqlConnection myCon = new SqlConnection();
myCon.ConnectionString = "server=.;uid=sa;pwd=123;database=book";
myCon.Open(); SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = sql;
myCmd.CommandType = CommandType.Text;
myCmd.Connection = myCon;
int count = int.Parse(myCmd.ExecuteScalar().ToString());
if (count > 0)
{
Frm_main main = new Frm_main();
main.Show();
this.Hide();
}
else
{
MessageBox.Show("用户名或密码错误!","登录错误",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
myCon.Close();
}catch(SqlException se)
{
MessageBox.Show(se.Message);
} }
下面是点击<登录>按钮的代码,如果输入的用户名和密码正确能成功找开主系统窗口,
但是如果用户名或密码错误,会提示:
int count = int.Parse(myCmd.ExecuteScalar().ToString());这句话错误!哪位大侠帮我看看,谢谢了!
private void but_login_Click(object sender, EventArgs e)
{
string user = this.txt_name.Text;
string pass = this.txt_pass.Text;
string sql = "select * from j_adminuser where userid='"+user+"' and password='"+pass+"'";
try
{
SqlConnection myCon = new SqlConnection();
myCon.ConnectionString = "server=.;uid=sa;pwd=123;database=book";
myCon.Open(); SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = sql;
myCmd.CommandType = CommandType.Text;
myCmd.Connection = myCon;
int count = int.Parse(myCmd.ExecuteScalar().ToString());
if (count > 0)
{
Frm_main main = new Frm_main();
main.Show();
this.Hide();
}
else
{
MessageBox.Show("用户名或密码错误!","登录错误",MessageBoxButtons.OK,MessageBoxIcon.Warning);
}
myCon.Close();
}catch(SqlException se)
{
MessageBox.Show(se.Message);
} }
解决方案:1.将SQLselect * from j_adminuser where userid=改为select count(*) from j_adminuser where userid=
2.用int.TryParse()...不过不推荐,除非你确定查出来的数据行第一列是数字,否则会有BUG的
try
{
SqlConnection myCon = new SqlConnection();
myCon.ConnectionString = "server=.;uid=sa;pwd=123;database=book";
myCon.Open(); SqlCommand myCmd = new SqlCommand();
myCmd.CommandText = sql;
myCmd.CommandType = CommandType.Text;
myCmd.Connection = myCon;
myCmd.Parameters.addRange(new SqlParameter[]{
new SqlParameter("@userId",user),
new SqlParameter("@pwd",pass)
});这样可以防止SQL注入,
正解,楼主查询出来的是一条记录,现在我们只要看合符用户名和密码的这条记录就成了。
不过,楼主这样写的容易被别人SQL注入:如在条件后在加上一个" or 1=1"是不是随便输入都可以登录呢?
你查询的所有列,应该要返回COUNT()
string sql = "select COUNT(*) from j_adminuser where userid='"+user+"' and password='"+pass+"'";