1

I faced some problem about sql connection issue. The problem is I have some code like this

function1()
{
    using (sqlconnection sc = new sqlconnection())
   {
      foo();
   }
}

foo is a function like below:
foo()
{
   using (sqlconnection sc = new sqlconnection())
  {
        dosomething;
  }
}

It seems that the sqlconnection in foo() cannot work. I'm wondering if it is a good idea to pass the sqlconnection into foo like foo(sc), or is it a good idea to take foo outside function1, or is there anyway to allow the sqlconnection inside foo works.

2
  • Without more specifics we can't really say. Are they trying to connect to the same server? Why do you need the connection in function1 if all it's doing is calling another method? Commented Sep 24, 2015 at 14:10
  • 1
    A connection is a session. Sessions are separate. In essence if you use a sqlcommand you tie it to a connection. Within one connection you can use only a single sqlreader, unless you enable mars. Multiple result sets. In short what you are trying should work, if it does not there is a different issue. You should show more code and real errors or exceptions. Commented Sep 24, 2015 at 14:11

1 Answer 1

3

No need of that, have your function foo to accepts a connection parameter and use the same connection instance in both places like below

function1()
{
    using (sqlconnection sc = new sqlconnection())
   {
      foo(sc);
   }
}

foo is a function like below:

foo(sqlconnection scc)
{
    sqlconnection sc = scc
    dosomething;
}
Sign up to request clarification or add additional context in comments.

3 Comments

seems a good idea, will sc inside foo affect sc inside function1? Since it is a connection, I don't know if it is a "copy" of sc inside function1 like other "virtual" object is.
@litaoshen, Yes it will since it's a reference type and not a value type but the sole idea is to use the same connection object instead having multiple one. You can use the same con object and can have different command object or same to that matter.
OK, I see. Thank you!

Your Answer

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.