登录代码需要帮助 [英] Login code need help please
本文介绍了登录代码需要帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一些帮助
i need some help
protected void btnLogin_Click(object sender, EventArgs e)
{
string query = "Select Count(*) From LoginInfo Where lo_name = @username And lo_password = @password";
int userId = 0;
using (SqlConnection conn = new SqlConnection(conStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@username", txtUsername.Text);
cmd.Parameters.AddWithValue("@password", txtPassword.Text);
cmd.Connection = conn;
conn.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
conn.Close();
}
if(userId>0)
{
Response.Redirect("Default.aspx");
}
else
{
lable1.Text = "Login Fialed";
}
}
}
当我点击登录按钮时,它会对以下代码给出错误>
when i clicked on login button it give error on the following codes
userId = Convert.ToInt32(cmd.ExecuteScalar());
推荐答案
object objValue = cmd.ExecuteScaler();
if (objValue != DbNull.Value)
{
userId = Convert.ToInt32(objValue);
}
尝试:
Try:
userId = (int) cmd.ExecuteScalar();
但请不要以明文形式存储密码!
见这里:密码存储:怎么做。 [ ^ ]
不要使用convert,使用(int)cmd.ExecuteScalar();
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v= vs.110%29.aspx [ ^ ]。
确保您的表数据类型确实是整数。在更糟糕的情况下,做动态转换来测试它:
Don't use convert, use(int)cmd.ExecuteScalar();
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx[^].
Make sure your table data type is really integer. In worse case, do dynamic cast to test it:
int value = cmd.ExecuteScalar() as int;
if (value != null)
// do something
else
// indicate that something goes wrong,
// for example, throw more informative exception
// then the cast exception
顺便说一句,转换
很少有用。例如,如果对象是字符串(编译时类型),最好使用解析方法,例如 int.Parse
或 int.TryParse
。
By the way, Convert
is rarely useful. For example, if the object is string (compile-time type), better use parse methods, such as int.Parse
or int.TryParse
.
这篇关于登录代码需要帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文