简体   繁体   中英

Can't read data from SqlDataReader

I'm trying to read from a database using DataReader in c#. And i have encountered an eror saying no data is present. Here is my code:

[WebMethod] //Login invoke 
    public string[] login(string u, string p) 
    {
        SqlConnection con = new SqlConnection();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = con;
        con.ConnectionString = @"******Database.mdf";
        cmd.Parameters.AddWithValue("@u", u);
        cmd.Parameters.AddWithValue("@p", p);
        cmd.CommandText = "SELECT username, pass, st, lastonline FROM admins WHERE username='@u' AND pass='@p' ";

        int st = 555;
        string lastonline = "";

        try
        {
            con.Open();
            SqlDataReader r = cmd.ExecuteReader();
            if (r.Read())
            {
                st = r.GetInt16(2);
                lastonline = r.GetString(3);
            }

            else
            {
                string[] x = new string[1] { "err" };
                return x;
            }

            r.Close();
            con.Close();
        }
        catch { }
        string[] arr = new string[3] { st.ToString(), lastonline, u };
        return arr;

it is not possible to have two rows that will have the same username and password so i'm not using a while loop for the r.Read(); . All this function gets a user name and a password, checks with the database if it has row that is compatable, gets the rest of the columns in that row and returns them in a string array. if nothing is there (no such user) it returnes an array with the value "x". The problem is that i allways get the "x" and when i force it to read, it pops-up the eror i mentioned above.

notes: *i tried running that query seperatly, it works fine. *i checked if the "u" and "p" values coorespond to "username" and "pass". they do so no problem here. *Looked up online, and here in stackoverflow, still nothing fitted my problem.

Any solutions?

You just don't need the quotes on the parameter names in a parameterised query:

  cmd.CommandText = "SELECT username, pass, st, lastonline FROM admins WHERE username=@u AND pass=@p";

Your version was trying to actually match against a username of @u and a password of @p .

That's because you are comparing the user name and password to the strings '@u' and '@p' instead of the parameter values @u and @p .

Remove the apostrophes around the parameters:

cmd.CommandText = "SELECT username, pass, st, lastonline FROM admins WHERE username=@u AND pass=@p ";

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