Methods to search for a client in MySQL by ID or by phone











up vote
1
down vote

favorite
1












I have this code that returns a client object, but to do it I use two methods.



How can I improve this to be more efficient and ensure it meets common standards?



    //Method that returns a client from a string
private static Cliente ObtenerCliente(string query)
{
try
{
abrirConexion(); //Static method that opens a connection

cmd = new MySqlCommand(query, mySqlConexion);
MySqlDataReader dataReader = cmd.ExecuteReader();

if (dataReader.Read())
{
return new Cliente(
Convert.ToInt32(dataReader["id_cliente"]),
dataReader["nombre_cliente"].ToString());
}
else
{
dataReader.Close();
return null;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cerrarConexion(); //Static method that closes the connection
}
}

//Method that returns a customer from a phone number given
public static Cliente ObtenerCliente_Telefono(string telefono)
{
string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
return ObtenerCliente(query); //Metodo que hace la consulta
}
public static Cliente ObtenerCliente_Id(int id)
{
string query = "SELECT * FROM clientes WHERE id_cliente = " + id + ';';
return ObtenerCliente(query);
}









share|improve this question
















bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
    – Raystafarian
    Mar 26 at 6:04








  • 3




    Mandatory reading for understanding SQL injection.
    – Roland Illig
    Mar 26 at 20:21










  • Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
    – BCdotWEB
    Oct 25 at 9:32















up vote
1
down vote

favorite
1












I have this code that returns a client object, but to do it I use two methods.



How can I improve this to be more efficient and ensure it meets common standards?



    //Method that returns a client from a string
private static Cliente ObtenerCliente(string query)
{
try
{
abrirConexion(); //Static method that opens a connection

cmd = new MySqlCommand(query, mySqlConexion);
MySqlDataReader dataReader = cmd.ExecuteReader();

if (dataReader.Read())
{
return new Cliente(
Convert.ToInt32(dataReader["id_cliente"]),
dataReader["nombre_cliente"].ToString());
}
else
{
dataReader.Close();
return null;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cerrarConexion(); //Static method that closes the connection
}
}

//Method that returns a customer from a phone number given
public static Cliente ObtenerCliente_Telefono(string telefono)
{
string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
return ObtenerCliente(query); //Metodo que hace la consulta
}
public static Cliente ObtenerCliente_Id(int id)
{
string query = "SELECT * FROM clientes WHERE id_cliente = " + id + ';';
return ObtenerCliente(query);
}









share|improve this question
















bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
    – Raystafarian
    Mar 26 at 6:04








  • 3




    Mandatory reading for understanding SQL injection.
    – Roland Illig
    Mar 26 at 20:21










  • Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
    – BCdotWEB
    Oct 25 at 9:32













up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





I have this code that returns a client object, but to do it I use two methods.



How can I improve this to be more efficient and ensure it meets common standards?



    //Method that returns a client from a string
private static Cliente ObtenerCliente(string query)
{
try
{
abrirConexion(); //Static method that opens a connection

cmd = new MySqlCommand(query, mySqlConexion);
MySqlDataReader dataReader = cmd.ExecuteReader();

if (dataReader.Read())
{
return new Cliente(
Convert.ToInt32(dataReader["id_cliente"]),
dataReader["nombre_cliente"].ToString());
}
else
{
dataReader.Close();
return null;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cerrarConexion(); //Static method that closes the connection
}
}

//Method that returns a customer from a phone number given
public static Cliente ObtenerCliente_Telefono(string telefono)
{
string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
return ObtenerCliente(query); //Metodo que hace la consulta
}
public static Cliente ObtenerCliente_Id(int id)
{
string query = "SELECT * FROM clientes WHERE id_cliente = " + id + ';';
return ObtenerCliente(query);
}









share|improve this question















I have this code that returns a client object, but to do it I use two methods.



How can I improve this to be more efficient and ensure it meets common standards?



    //Method that returns a client from a string
private static Cliente ObtenerCliente(string query)
{
try
{
abrirConexion(); //Static method that opens a connection

cmd = new MySqlCommand(query, mySqlConexion);
MySqlDataReader dataReader = cmd.ExecuteReader();

if (dataReader.Read())
{
return new Cliente(
Convert.ToInt32(dataReader["id_cliente"]),
dataReader["nombre_cliente"].ToString());
}
else
{
dataReader.Close();
return null;
}
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
cerrarConexion(); //Static method that closes the connection
}
}

//Method that returns a customer from a phone number given
public static Cliente ObtenerCliente_Telefono(string telefono)
{
string query = "SELECT * FROM clientes WHERE (telefono1_cliente = '" + telefono + "' OR telefono2_cliente = '" + telefono + "');";
return ObtenerCliente(query); //Metodo que hace la consulta
}
public static Cliente ObtenerCliente_Id(int id)
{
string query = "SELECT * FROM clientes WHERE id_cliente = " + id + ';';
return ObtenerCliente(query);
}






c# mysql






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 26 at 6:07









200_success

127k15148411




127k15148411










asked Mar 26 at 5:54









Alejandro Arelis

61




61





bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
    – Raystafarian
    Mar 26 at 6:04








  • 3




    Mandatory reading for understanding SQL injection.
    – Roland Illig
    Mar 26 at 20:21










  • Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
    – BCdotWEB
    Oct 25 at 9:32


















  • Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
    – Raystafarian
    Mar 26 at 6:04








  • 3




    Mandatory reading for understanding SQL injection.
    – Roland Illig
    Mar 26 at 20:21










  • Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
    – BCdotWEB
    Oct 25 at 9:32
















Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
– Raystafarian
Mar 26 at 6:04






Welcome to Code Review! I edited your question a bit in hopes that it wouldn't be flagged as off-topic. If I significantly changed what you meant, please just let me know and we can fix it.
– Raystafarian
Mar 26 at 6:04






3




3




Mandatory reading for understanding SQL injection.
– Roland Illig
Mar 26 at 20:21




Mandatory reading for understanding SQL injection.
– Roland Illig
Mar 26 at 20:21












Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
– BCdotWEB
Oct 25 at 9:32




Instead of writing ADO.NET code, why not use Dapper? github.com/StackExchange/Dapper/blob/master/Dapper.Tests/…
– BCdotWEB
Oct 25 at 9:32










2 Answers
2






active

oldest

votes

















up vote
0
down vote













Nothing wrong with Cliente ObtenerCliente accepting the query text.



Suffers from non-deterministic. You are only going to get the first but without an order by then SQL will just pick one for you.



using is a better approach in my opinion



For sure I don't like




Static method that opens a connection




Create the connection and let it be properly disposed



private static Cliente ObtenerCliente(string query)
{
using (Connection mySqlConexion = new Connection(conString))
{
try
{
//abrirConexion(); //Static method that opens a connection
mySqlConexion.Open();
using (cmd = new MySqlCommand(query, mySqlConexion))
{
using (MySqlDataReader dataReader = cmd.ExecuteReader())
{
if (dataReader.Read())
{
return new Cliente(
Convert.ToInt32(dataReader["id_cliente"]),
dataReader["nombre_cliente"].ToString());
}
else
{
//dataReader.Close(); let the using dispose
return null;
}
}
}
}
catch (MySqlException e)
{
MessageBox.Show(e.ToString());
return null;
}
finally
{
//cerrarConexion(); //Static method that closes the connection
}
}
}





share|improve this answer






























    up vote
    0
    down vote













    Extending paparazzo's answer, I would use a tertiary to return the result. I also like the descriptiveness of default rather than null:



    return dataReader.Read()
    ? new Cliente(Convert.ToInt32(dataReader["id_cliente"]),
    dataReader["nombre_cliente"].ToString())
    : default(Cliente);


    Also consider using Top(1) in the queries, together with the order by suggestion, as the code only processes one row






    share|improve this answer





















      Your Answer





      StackExchange.ifUsing("editor", function () {
      return StackExchange.using("mathjaxEditing", function () {
      StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
      StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
      });
      });
      }, "mathjax-editing");

      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: "196"
      };
      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: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      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%2fcodereview.stackexchange.com%2fquestions%2f190474%2fmethods-to-search-for-a-client-in-mysql-by-id-or-by-phone%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      0
      down vote













      Nothing wrong with Cliente ObtenerCliente accepting the query text.



      Suffers from non-deterministic. You are only going to get the first but without an order by then SQL will just pick one for you.



      using is a better approach in my opinion



      For sure I don't like




      Static method that opens a connection




      Create the connection and let it be properly disposed



      private static Cliente ObtenerCliente(string query)
      {
      using (Connection mySqlConexion = new Connection(conString))
      {
      try
      {
      //abrirConexion(); //Static method that opens a connection
      mySqlConexion.Open();
      using (cmd = new MySqlCommand(query, mySqlConexion))
      {
      using (MySqlDataReader dataReader = cmd.ExecuteReader())
      {
      if (dataReader.Read())
      {
      return new Cliente(
      Convert.ToInt32(dataReader["id_cliente"]),
      dataReader["nombre_cliente"].ToString());
      }
      else
      {
      //dataReader.Close(); let the using dispose
      return null;
      }
      }
      }
      }
      catch (MySqlException e)
      {
      MessageBox.Show(e.ToString());
      return null;
      }
      finally
      {
      //cerrarConexion(); //Static method that closes the connection
      }
      }
      }





      share|improve this answer



























        up vote
        0
        down vote













        Nothing wrong with Cliente ObtenerCliente accepting the query text.



        Suffers from non-deterministic. You are only going to get the first but without an order by then SQL will just pick one for you.



        using is a better approach in my opinion



        For sure I don't like




        Static method that opens a connection




        Create the connection and let it be properly disposed



        private static Cliente ObtenerCliente(string query)
        {
        using (Connection mySqlConexion = new Connection(conString))
        {
        try
        {
        //abrirConexion(); //Static method that opens a connection
        mySqlConexion.Open();
        using (cmd = new MySqlCommand(query, mySqlConexion))
        {
        using (MySqlDataReader dataReader = cmd.ExecuteReader())
        {
        if (dataReader.Read())
        {
        return new Cliente(
        Convert.ToInt32(dataReader["id_cliente"]),
        dataReader["nombre_cliente"].ToString());
        }
        else
        {
        //dataReader.Close(); let the using dispose
        return null;
        }
        }
        }
        }
        catch (MySqlException e)
        {
        MessageBox.Show(e.ToString());
        return null;
        }
        finally
        {
        //cerrarConexion(); //Static method that closes the connection
        }
        }
        }





        share|improve this answer

























          up vote
          0
          down vote










          up vote
          0
          down vote









          Nothing wrong with Cliente ObtenerCliente accepting the query text.



          Suffers from non-deterministic. You are only going to get the first but without an order by then SQL will just pick one for you.



          using is a better approach in my opinion



          For sure I don't like




          Static method that opens a connection




          Create the connection and let it be properly disposed



          private static Cliente ObtenerCliente(string query)
          {
          using (Connection mySqlConexion = new Connection(conString))
          {
          try
          {
          //abrirConexion(); //Static method that opens a connection
          mySqlConexion.Open();
          using (cmd = new MySqlCommand(query, mySqlConexion))
          {
          using (MySqlDataReader dataReader = cmd.ExecuteReader())
          {
          if (dataReader.Read())
          {
          return new Cliente(
          Convert.ToInt32(dataReader["id_cliente"]),
          dataReader["nombre_cliente"].ToString());
          }
          else
          {
          //dataReader.Close(); let the using dispose
          return null;
          }
          }
          }
          }
          catch (MySqlException e)
          {
          MessageBox.Show(e.ToString());
          return null;
          }
          finally
          {
          //cerrarConexion(); //Static method that closes the connection
          }
          }
          }





          share|improve this answer














          Nothing wrong with Cliente ObtenerCliente accepting the query text.



          Suffers from non-deterministic. You are only going to get the first but without an order by then SQL will just pick one for you.



          using is a better approach in my opinion



          For sure I don't like




          Static method that opens a connection




          Create the connection and let it be properly disposed



          private static Cliente ObtenerCliente(string query)
          {
          using (Connection mySqlConexion = new Connection(conString))
          {
          try
          {
          //abrirConexion(); //Static method that opens a connection
          mySqlConexion.Open();
          using (cmd = new MySqlCommand(query, mySqlConexion))
          {
          using (MySqlDataReader dataReader = cmd.ExecuteReader())
          {
          if (dataReader.Read())
          {
          return new Cliente(
          Convert.ToInt32(dataReader["id_cliente"]),
          dataReader["nombre_cliente"].ToString());
          }
          else
          {
          //dataReader.Close(); let the using dispose
          return null;
          }
          }
          }
          }
          catch (MySqlException e)
          {
          MessageBox.Show(e.ToString());
          return null;
          }
          finally
          {
          //cerrarConexion(); //Static method that closes the connection
          }
          }
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 26 at 18:41

























          answered Mar 26 at 14:25









          paparazzo

          4,9911733




          4,9911733
























              up vote
              0
              down vote













              Extending paparazzo's answer, I would use a tertiary to return the result. I also like the descriptiveness of default rather than null:



              return dataReader.Read()
              ? new Cliente(Convert.ToInt32(dataReader["id_cliente"]),
              dataReader["nombre_cliente"].ToString())
              : default(Cliente);


              Also consider using Top(1) in the queries, together with the order by suggestion, as the code only processes one row






              share|improve this answer

























                up vote
                0
                down vote













                Extending paparazzo's answer, I would use a tertiary to return the result. I also like the descriptiveness of default rather than null:



                return dataReader.Read()
                ? new Cliente(Convert.ToInt32(dataReader["id_cliente"]),
                dataReader["nombre_cliente"].ToString())
                : default(Cliente);


                Also consider using Top(1) in the queries, together with the order by suggestion, as the code only processes one row






                share|improve this answer























                  up vote
                  0
                  down vote










                  up vote
                  0
                  down vote









                  Extending paparazzo's answer, I would use a tertiary to return the result. I also like the descriptiveness of default rather than null:



                  return dataReader.Read()
                  ? new Cliente(Convert.ToInt32(dataReader["id_cliente"]),
                  dataReader["nombre_cliente"].ToString())
                  : default(Cliente);


                  Also consider using Top(1) in the queries, together with the order by suggestion, as the code only processes one row






                  share|improve this answer












                  Extending paparazzo's answer, I would use a tertiary to return the result. I also like the descriptiveness of default rather than null:



                  return dataReader.Read()
                  ? new Cliente(Convert.ToInt32(dataReader["id_cliente"]),
                  dataReader["nombre_cliente"].ToString())
                  : default(Cliente);


                  Also consider using Top(1) in the queries, together with the order by suggestion, as the code only processes one row







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 28 at 22:08









                  adrianJ

                  511




                  511






























                       

                      draft saved


                      draft discarded



















































                       


                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f190474%2fmethods-to-search-for-a-client-in-mysql-by-id-or-by-phone%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'