我有一个非常简单的方法,用来检查用户是否有正确的密码。为什么它不起作用的任何帮助?这适用于Microsoft SQL Server。
public bool UserNameExists()
{
using (SqlConnection con = new SqlConnection("CONNECTION STRING AQUI!"))
{
con.Open();
try
{
using (SqlCommand command = new SqlCommand(string.Format("SELECT * FROM Policia WHERE NumeroPlaca = '{0}' AND Password = '{1}'", Session.Contents["username"], Session.Contents["password"]), con))
{
SqlDataReader reader = command.ExecuteReader();
if (reader.FieldCount > 0)
{
return true;
}
else
{
return false;
}
}
}
catch
{
}
return false;
}
}
答案 0 :(得分:4)
你也可以这样做:
"SELECT COUNT(*) FROM Policia..."
然后:
int result = Convert.ToInt32(command.ExecuteScalar());
if (result > 0)
{
return true;
}
else
{
return false;
}
完整代码:
public bool UserNameExists()
{
int result = int.MinValue;
using (SqlConnection connection = new SqlConnection(_connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "SELECT COUNT(*) FROM Policia WHERE NumeroPlaca = @username AND Password = @password";
command.Parameters.Clear();
command.Parameters.Add("@username", SqlDbType.VarChar).Value = Session.Contents["username"];
command.Parameters.Add("@password", SqlDbType.VarChar).Value = Session.Contents["password"];
result = Convert.ToInt32(command.ExecuteScalar());
}
if (result > 0)
{
return true;
}
{
return false;
}
}
答案 1 :(得分:3)
FieldCount获取当前行中的列数,该列始终为非零。您正在寻找结果集中的行数。使用HasRows属性。