1

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?

asked Sep 22, 2015 at 23:42

2 Answers 2

3

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.

answered Sep 22, 2015 at 23:46
0
1

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 ";
answered Sep 22, 2015 at 23:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.