0

I'm doing some SQL connections with the 'using' command to dispose/close connections for me. If I pass items to a string from within the using command, will they remain once the connection is closed/disposed?

If it does, what is the best way to make sure items are kept in the string rather than being disposed so that I can use them later on.

undefined
  • 33,537
  • 22
  • 129
  • 198
PipBoy
  • 1,127
  • 4
  • 11
  • 16

3 Answers3

0

If I understand correctly, you mean objects passed as the commands parameters? As far as I know they are not disposed when the command is disposed. The easiest way to make sure they are correctly dispose is to manually access the SqlCommand.Parameters.

For example, you can use the following code.

if (command.Parameters != null)
{
    foreach (object parameter in command.Parameters)
    {
        IDisposable disposableParameter = parameter as IDisposable;
        if (disposableParameter != null)
        {
            disposableParameter.Dispose();
        }
    }
}
Marek Dzikiewicz
  • 2,844
  • 1
  • 22
  • 24
0

I think you mess up several concepts. When you construct an SQL query you have 2 options, construct it using a string, like:

"Select from " + TableName + " where " + ColumnName + "=" + ColumnValue ...

Very bad! Never do this, you have to use parameters, like:

"Select from " + "TableName + " where " + ColumnName + "=@Value"

And after inject the value of interest using SqlParameter.

In both cases the lifetime of the actual value has nothing to do with a SQL string. The value lifetime depends how you use a variable that holds that value.

Hope this helps.

Tigran
  • 61,654
  • 8
  • 86
  • 123
0

Strings are always passed by value. So, if I understand your question correctly, your strings should stay untouched. using statement will only dispose the command.

ElDog
  • 1,230
  • 1
  • 10
  • 21