I have this very simple method called to check if a user has a correct password. Any help on why it isn't working? This is for 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;
}
}
You could also do:
"SELECT COUNT(*) FROM Policia..."
And then:
int result = Convert.ToInt32(command.ExecuteScalar());
if (result > 0)
{
return true;
}
else
{
return false;
}
Full code:
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;
}
}
FieldCount gets the number of columns in the current row, which will always be non-zero. You're looking for the number of rows in the result set. Use the HasRows property.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.