locked
problem accessing database RRS feed

  • Question

  • User-1581583421 posted

    hi i'm trying to access a database, this is my code

    public class Conexion
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Acceso"].ToString());
            public static string Mostrar()
            {
                SqlCommand query;
                try
                {
                    string valor;
                    query = new SqlCommand("select hratrn from Despachos where nrotrn=10");
                    con.Open();
                    SqlDataReader lector = query.ExecuteReader();
                    if (lector.Read())
                        valor = lector["hratrn"].ToString();
                    else
                        valor = "error";
                    con.Close();
                    return valor;
                }
                catch
                {
                    con.Close();
                    return "error";
                }
            }
        }

    where "Acceso" is my connection string name in the web.config file

    but when i run my app i get this error: 

    An object reference is required for the non-static field, method, or property 'VideoWeb.Conexion.com'

    any idea?

    Really thank you


    Tuesday, April 23, 2013 12:57 PM

Answers

  • User-1137493631 posted

    make sqlconnection as static as like 

    static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Acceso"].ToString());

    or just place your connection object inside Mstrar method becuase that is specified as static / or just you cansimply remove that static keyword from Mostrar method 

    public  string Mostrar()




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 23, 2013 1:13 PM

All replies

  • User-1137493631 posted

    make sqlconnection as static as like 

    static SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Acceso"].ToString());

    or just place your connection object inside Mstrar method becuase that is specified as static / or just you cansimply remove that static keyword from Mostrar method 

    public  string Mostrar()




    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, April 23, 2013 1:13 PM
  • User-1581583421 posted

    cool! that worked, really thank you man

    Tuesday, April 23, 2013 1:16 PM
  • User1992938117 posted

     public static string Mostrar()
            {

    Since the Mostrar() method is static, it can't access the con.

    Use as below:

     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Acceso"].ToString());
    
        private string Mostrar()
        {
         ....
        }



    Tuesday, April 23, 2013 1:16 PM