Can't find id by a given user name









up vote
0
down vote

favorite












I am trying to get the user id from the user's table called userDataTbl(in my MySQL database) by a user name. However, when I run the code below it keeps returning -1 and the result parameter keeps being -1 as if it didn't find the user.



I have also used the method below in order to check if a username already exists in the table-and then I just checked if the result is greater than 0 to return that it exists and otherwise that it doesn't exists, but it didn't work there either and the result kept being -1 even though I put names that did exist in the table. I have tried debugging but it didn't tell me much because it doesn't really show me what the computer does in the query so that I'll know what's wrong with it.
this is the code :



//returns a user id according to a name
public int theId(string name)

SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
command2.Parameters.AddWithValue("@username", name);
int result = command2.ExecuteNonQuery();
if (result > 0)

SqlDataReader reader = command2.ExecuteReader();
reader.Read(); // we have only 1 row
try

string foundId = String.Format("0", reader["userId"]);
int id = Convert.ToInt32(foundId);
return id;

catch

return 0;


else

return -1;




I will be very grateful for any help, it's really important for me.










share|improve this question



























    up vote
    0
    down vote

    favorite












    I am trying to get the user id from the user's table called userDataTbl(in my MySQL database) by a user name. However, when I run the code below it keeps returning -1 and the result parameter keeps being -1 as if it didn't find the user.



    I have also used the method below in order to check if a username already exists in the table-and then I just checked if the result is greater than 0 to return that it exists and otherwise that it doesn't exists, but it didn't work there either and the result kept being -1 even though I put names that did exist in the table. I have tried debugging but it didn't tell me much because it doesn't really show me what the computer does in the query so that I'll know what's wrong with it.
    this is the code :



    //returns a user id according to a name
    public int theId(string name)

    SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
    command2.Parameters.AddWithValue("@username", name);
    int result = command2.ExecuteNonQuery();
    if (result > 0)

    SqlDataReader reader = command2.ExecuteReader();
    reader.Read(); // we have only 1 row
    try

    string foundId = String.Format("0", reader["userId"]);
    int id = Convert.ToInt32(foundId);
    return id;

    catch

    return 0;


    else

    return -1;




    I will be very grateful for any help, it's really important for me.










    share|improve this question

























      up vote
      0
      down vote

      favorite









      up vote
      0
      down vote

      favorite











      I am trying to get the user id from the user's table called userDataTbl(in my MySQL database) by a user name. However, when I run the code below it keeps returning -1 and the result parameter keeps being -1 as if it didn't find the user.



      I have also used the method below in order to check if a username already exists in the table-and then I just checked if the result is greater than 0 to return that it exists and otherwise that it doesn't exists, but it didn't work there either and the result kept being -1 even though I put names that did exist in the table. I have tried debugging but it didn't tell me much because it doesn't really show me what the computer does in the query so that I'll know what's wrong with it.
      this is the code :



      //returns a user id according to a name
      public int theId(string name)

      SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
      command2.Parameters.AddWithValue("@username", name);
      int result = command2.ExecuteNonQuery();
      if (result > 0)

      SqlDataReader reader = command2.ExecuteReader();
      reader.Read(); // we have only 1 row
      try

      string foundId = String.Format("0", reader["userId"]);
      int id = Convert.ToInt32(foundId);
      return id;

      catch

      return 0;


      else

      return -1;




      I will be very grateful for any help, it's really important for me.










      share|improve this question















      I am trying to get the user id from the user's table called userDataTbl(in my MySQL database) by a user name. However, when I run the code below it keeps returning -1 and the result parameter keeps being -1 as if it didn't find the user.



      I have also used the method below in order to check if a username already exists in the table-and then I just checked if the result is greater than 0 to return that it exists and otherwise that it doesn't exists, but it didn't work there either and the result kept being -1 even though I put names that did exist in the table. I have tried debugging but it didn't tell me much because it doesn't really show me what the computer does in the query so that I'll know what's wrong with it.
      this is the code :



      //returns a user id according to a name
      public int theId(string name)

      SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
      command2.Parameters.AddWithValue("@username", name);
      int result = command2.ExecuteNonQuery();
      if (result > 0)

      SqlDataReader reader = command2.ExecuteReader();
      reader.Read(); // we have only 1 row
      try

      string foundId = String.Format("0", reader["userId"]);
      int id = Convert.ToInt32(foundId);
      return id;

      catch

      return 0;


      else

      return -1;




      I will be very grateful for any help, it's really important for me.







      c# sql .net






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 11 at 1:19









      Bradley Grainger

      19.2k46486




      19.2k46486










      asked Nov 10 at 7:08









      harpagon mulier

      61




      61






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          1
          down vote



          accepted










          Based on MSDN:




          For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.




          If you want to get the number of rows affected by the SELECT command and save it to an int variable you can use Count and ExecuteScalar:



          "SELECT COUNT(userId)..."
          var result = (int)command2.ExecuteScalar();





          share|improve this answer





























            up vote
            0
            down vote













            I think int result = command2.ExecuteNonQuery(); line causes problem for you remove that line, change the code as below and run it



            public int theId(string name)

            SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
            command2.Parameters.AddWithValue("@username", name);
            this.connection.open();
            try

            SqlDataReader reader = command2.ExecuteReader();
            if(reader.HasRows)

            while(reader.Read())

            string foundId = String.Format("0", reader["userId"]);
            int id = Convert.ToInt32(foundId);
            return id;


            else

            return -1;


            catch(Exception ex)






            Hope this helps you - Happy coding !!






            share|improve this answer






















              Your Answer






              StackExchange.ifUsing("editor", function ()
              StackExchange.using("externalEditor", function ()
              StackExchange.using("snippets", function ()
              StackExchange.snippets.init();
              );
              );
              , "code-snippets");

              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "1"
              ;
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function()
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled)
              StackExchange.using("snippets", function()
              createEditor();
              );

              else
              createEditor();

              );

              function createEditor()
              StackExchange.prepareEditor(
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader:
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              ,
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              );



              );













               

              draft saved


              draft discarded


















              StackExchange.ready(
              function ()
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236789%2fcant-find-id-by-a-given-user-name%23new-answer', 'question_page');

              );

              Post as a guest






























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              1
              down vote



              accepted










              Based on MSDN:




              For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.




              If you want to get the number of rows affected by the SELECT command and save it to an int variable you can use Count and ExecuteScalar:



              "SELECT COUNT(userId)..."
              var result = (int)command2.ExecuteScalar();





              share|improve this answer


























                up vote
                1
                down vote



                accepted










                Based on MSDN:




                For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.




                If you want to get the number of rows affected by the SELECT command and save it to an int variable you can use Count and ExecuteScalar:



                "SELECT COUNT(userId)..."
                var result = (int)command2.ExecuteScalar();





                share|improve this answer
























                  up vote
                  1
                  down vote



                  accepted







                  up vote
                  1
                  down vote



                  accepted






                  Based on MSDN:




                  For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.




                  If you want to get the number of rows affected by the SELECT command and save it to an int variable you can use Count and ExecuteScalar:



                  "SELECT COUNT(userId)..."
                  var result = (int)command2.ExecuteScalar();





                  share|improve this answer














                  Based on MSDN:




                  For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.




                  If you want to get the number of rows affected by the SELECT command and save it to an int variable you can use Count and ExecuteScalar:



                  "SELECT COUNT(userId)..."
                  var result = (int)command2.ExecuteScalar();






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 10 at 13:50

























                  answered Nov 10 at 7:12









                  S.Akbari

                  28.9k93369




                  28.9k93369






















                      up vote
                      0
                      down vote













                      I think int result = command2.ExecuteNonQuery(); line causes problem for you remove that line, change the code as below and run it



                      public int theId(string name)

                      SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
                      command2.Parameters.AddWithValue("@username", name);
                      this.connection.open();
                      try

                      SqlDataReader reader = command2.ExecuteReader();
                      if(reader.HasRows)

                      while(reader.Read())

                      string foundId = String.Format("0", reader["userId"]);
                      int id = Convert.ToInt32(foundId);
                      return id;


                      else

                      return -1;


                      catch(Exception ex)






                      Hope this helps you - Happy coding !!






                      share|improve this answer


























                        up vote
                        0
                        down vote













                        I think int result = command2.ExecuteNonQuery(); line causes problem for you remove that line, change the code as below and run it



                        public int theId(string name)

                        SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
                        command2.Parameters.AddWithValue("@username", name);
                        this.connection.open();
                        try

                        SqlDataReader reader = command2.ExecuteReader();
                        if(reader.HasRows)

                        while(reader.Read())

                        string foundId = String.Format("0", reader["userId"]);
                        int id = Convert.ToInt32(foundId);
                        return id;


                        else

                        return -1;


                        catch(Exception ex)






                        Hope this helps you - Happy coding !!






                        share|improve this answer
























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          I think int result = command2.ExecuteNonQuery(); line causes problem for you remove that line, change the code as below and run it



                          public int theId(string name)

                          SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
                          command2.Parameters.AddWithValue("@username", name);
                          this.connection.open();
                          try

                          SqlDataReader reader = command2.ExecuteReader();
                          if(reader.HasRows)

                          while(reader.Read())

                          string foundId = String.Format("0", reader["userId"]);
                          int id = Convert.ToInt32(foundId);
                          return id;


                          else

                          return -1;


                          catch(Exception ex)






                          Hope this helps you - Happy coding !!






                          share|improve this answer














                          I think int result = command2.ExecuteNonQuery(); line causes problem for you remove that line, change the code as below and run it



                          public int theId(string name)

                          SqlCommand command2 = new SqlCommand("Select userId from dbo.userDataTbl where userName=@username", this.connection);
                          command2.Parameters.AddWithValue("@username", name);
                          this.connection.open();
                          try

                          SqlDataReader reader = command2.ExecuteReader();
                          if(reader.HasRows)

                          while(reader.Read())

                          string foundId = String.Format("0", reader["userId"]);
                          int id = Convert.ToInt32(foundId);
                          return id;


                          else

                          return -1;


                          catch(Exception ex)






                          Hope this helps you - Happy coding !!







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 10 at 12:13









                          S.Akbari

                          28.9k93369




                          28.9k93369










                          answered Nov 10 at 7:26









                          Rahul Swamynathan

                          67318




                          67318



























                               

                              draft saved


                              draft discarded















































                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function ()
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53236789%2fcant-find-id-by-a-given-user-name%23new-answer', 'question_page');

                              );

                              Post as a guest














































































                              這個網誌中的熱門文章

                              How to read a connectionString WITH PROVIDER in .NET Core?

                              In R, how to develop a multiplot heatmap.2 figure showing key labels successfully

                              Museum of Modern and Contemporary Art of Trento and Rovereto