0

I have a code for fetching customer_id and I use a SqlDataReader for reading customer_id from SQL Server. I test witch using breakpoint and step by step debugging and I understand the SqlDataReader condition was not compile and compiler jump straight in to the connection.close line:

   string strQuery = "select customer_id from Registration where username=@username and password=@password";
    SqlConnection connection1 = DBConnection.getConnection();
    connection1.Open();

   SqlCommand cmd = new SqlCommand();
   cmd.Connection = connection1;
   cmd.CommandText = strQuery;

   cmd.Parameters.AddWithValue("username", txt1_username.Text);
   cmd.Parameters.AddWithValue("password", txt2_password.Text);

   string customer_id = cmd.ExecuteScalar() as string;

   connection1.Close();

   if (customer_id == null)
    {
    Messages myMsg = new Messages();
    myMsg.CreateMessageAlert("The User does not Registered or your using incorect username or password");

     } 

      else {
     Session["customer_id"] = customer_id; 
        }
Ahmed
  • 9
  • 3

3 Answers3

0

updated

        string strQuery = "select count(*) from Employee where  FullName=@username";
        SqlConnection connection = DBConnection.getConnection();
        connection.Open();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = connection;
        cmd.CommandText = strQuery;

        cmd.Parameters.AddWithValue("username", txt1_username.Text);
        cmd.Parameters.AddWithValue("password", txt2_password.Text);

        int intRowCount = (int)cmd.ExecuteScalar();
        txt1_username.Text = intRowCount.ToString();
        if (intRowCount == 1)
        {
            string strquery = "select customer_id from Registration where  username=@username and password=@password";
            SqlCommand cmd2 = new SqlCommand();
            cmd2.Connection = connection;
            cmd2.CommandText = strquery;
            cmd2.Parameters.AddWithValue("username", txt1_username.Text);
            cmd2.Parameters.AddWithValue("password", txt2_password.Text);
            SqlDataReader reader = cmd2.ExecuteReader();
            if (reader.Read())
            {
                string customerID = reader[0].ToString();                    
            }
        }
        connection.Close();`

This is complete solution for your issue. Do not need to open connection everytime. just make sure, connection is being closed once it's used.

Sandip
  • 981
  • 1
  • 6
  • 22
  • i correct my mistake . but again the compiler was jump straight for connection.close and sqldatareader was not compile .why sqldatareader condition was not compile? – Ahmed Jul 14 '16 at 07:15
  • @Ahmed I have updated the comment. find the complete solution with optimised code. – Sandip Jul 14 '16 at 08:23
0

Although the issue is not very clear, you can try to revise the code taking following into account:

  • There is no need to open/close db connection for every sql query in a method. Open it once, execute all queries, close. That will make code clear and faster.
  • As you take connection from somewhere else, make sure it is closed before you open it (Example: Check if SQL Connection is Open or Closed)
  • You run 2 queries and in both cases you get only 1 result (select count(*), select customer_id). Why then in first case you do ExecuteScalar() and ExecuteReader() in the other?
  • The other thought is there is no need to have 2 SqlCommand(), etc if you need to return results of 2 queries. Read about Retrieving Multiple Result Sets using NextResult
  • And last but not least - it seems you need to check if user is already registered and if true, get his id. Why not do it in one shot? The second query is good for both cases - if user does not exist, query will not return any result, if he does - his id will be returned. Doing this way, you would need only one query and less coding.

UPDATE:

The updated code looks more clear and straightforward, but you didn't get the point of my last comment. If you select count(customer_id) you get a count that you don't need. Why not simply select customer_id and check if it was returned or not?

Example:

//string strQuery = "select count(customer_id) from Registration where username=@username and password=@password";
string strQuery = "select customer_id from Registration where username=@username and password=@password";
SqlConnection connection1 = DBConnection.getConnection();
connection1.Open();

SqlCommand cmd = new SqlCommand();
cmd.Connection = connection1;
cmd.CommandText = strQuery;

cmd.Parameters.AddWithValue("username", txt1_username.Text);
cmd.Parameters.AddWithValue("password", txt2_password.Text);

//int intRowCount = (int)cmd.ExecuteScalar();
string customer_id = cmd.ExecuteScalar() as string;

//txt1_username.Text = intRowCount.ToString(); <-- What's this?
connection1.Close();

//if (intRowCount == 1)
if (customer_id == null)
{
   // user does not exist, because sql returned no rows
   ... <-- do something here
} else {
   Session["customer_id"] = customer_id; 
}

UPDATE #2:

To troubleshoot

  1. Make sure txt1_username.Text and txt2_password.Text have expected values. It could be that you reset the Text somewhere and that could be the reason why the query returned no result. Try to hardcode the value in the code, for example,

    cmd2.Parameters.AddWithValue("username", "admin");
    cmd2.Parameters.AddWithValue("password", "123");
    
  2. Copy-paste entire sql in Sql Server Management Studio (or other tool) and run it from here to ensure what result it returned.

  3. Make sure you execute it against correct database (maybe you have different databases with same tables where data is different).
Community
  • 1
  • 1
user2316116
  • 6,726
  • 1
  • 21
  • 35
  • thank you , you are open my eyes & mind , i change the query . now when i have a registered user how can get customer_id and put it in to the session variable? please see my edited code . – Ahmed Jul 15 '16 at 06:50
  • i change the code , but i have a user in the database with that username and password , but always show me the message(The User does not Registered ...) . i run with breakpoint and i cant understand Why should the customer_id be Null ? This is despite the fact that such users with correct username and password was stored in the database . – Ahmed Jul 15 '16 at 08:12
  • Troubleshoot as I described in the updated post. The code is correct now and it looks as a data issue either in user input (or the way you get the data from textboxes) or in the database. – user2316116 Jul 15 '16 at 09:13
  • i test with hardcode and i do not success , at next i test query in the sql server and it returned all customer_id in the Tableو This indicates that the query is correct . i de atach all DataBase Except this db in the sqlserver . i checked the textboxes but the program was not work . i think may the problem is come from executing query command ' string customer_id = cmd.ExecuteScalar() as string;' dont you? – Ahmed Jul 16 '16 at 06:55
  • yes i was true . the problem is come from as string from executing line code . i change that to Tostring() and it work . – Ahmed Jul 16 '16 at 06:59
0

This is because your username is no longer the username. It is actually 1 because of the line

int intRowCount = (int) cmd.ExecuteScalar();
txt1_username.Text = intRowCount.ToString(); <-- RED FLAG

So in the inside the If, you are actually running

SELECT customer_id FROM registration WHERE username=1 and password=my_password

Comment line 15 and you should do fine.

athar13
  • 382
  • 1
  • 8