简体   繁体   中英

MySql Query does not return any value even though it Exists in the table (C# Asp.net)

I encountered a problem while trying to verify if a value exists in the database. I use Visual Studio 2017. I wrote a function that checks if Username is in the database table:

protected bool userIsAdmin(string user)
{
    SqlConnection con = new SqlConnection(connectionString);
    con.Open();
    string loginQuery = "select count(*) from AdminTable where User= @Username";
    SqlCommand command = new SqlCommand(loginQuery, con);

    command.Parameters.AddWithValue("@Username", user);
    user = user.Trim();

    int rows;
    rows = (int)command.ExecuteScalar();

    if (rows != 0)
    {
        OutputLabel.Text = "You are logged";
        return true;
    }
    else
    {
        OutputLabel.Text = "Try again";
        return false;
    }
}

I eliminated the probability of an outside error by calling this function like this: if(userIsAdmin("uia94881"){...}

My database table: enter image description here

Replace your script as below,

string loginQuery = "select count(*) from AdminTable where [User]= @Username";

because User is a built in function in SQL Server, which will give you the Database username.

SqlConnection connection = new SqlConnection("PUT YOUR CONNECTION STRING HERE");

string loginQuery = "SELECT (User) FROM AdminTable WHERE User = @Username";
SqlDataAdapter adpt = new SqlDataAdapter(loginQuery, connection);

adapt.SelectCommand.Parameters.AddWithValue("@Username", user);
DataSet usr = new DataSet();
adapt.Fill(usr)

foreach(DataRow dr in usr.Tables[0].Rows)
{ 
  string user += usr.Tables[0].Rows[0]["User"].ToString();
}
if(user != "")
{
    OutputLabel.Text = "Try again";
    return false;
}
else
{
    OutputLabel.Text = "You are logged";
    return true;
}

Try this instead!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM