开发者

Is it possible to reuse a connection when accessing multiple tables in C#?

开发者 https://www.devze.com 2023-03-14 15:41 出处:网络
I am new to C#. I have a program which reads multiple tables in single database. Suppose if i am reading table A so before reading this I have to connect to database in C#. after this I have to 开发者

I am new to C#. I have a program which reads multiple tables in single database. Suppose if i am reading table A so before reading this I have to connect to database in C#. after this I have to 开发者_运维问答fetch some information from table B. Do I have to give the server info, userid and password again to connect to database?


You can use a single connection for both tables as long as the user has permissions to read from table A and table B.

For example, if you're using SqlCommands and a SqlConnection, set the connection as follows:

SqlConnection connection;
SqlCommand commandA;
SqlCommand commandB;

connection = new SqlConnection("some connection string");
connection.Open();

commandA = new SqlCommand();
commandA.Connection = connection;
commandB = new SqlCommand();
commandB.Connection = connection;

You can then set the CommandType and CommandText on both commandA and commandB as needed. As long as the connection is still open and the user has access to both tables, you'll be set.


We would need to see your code (please mask out your actual user credentials) but the short answer will be yes if you are using a seperate connection to perform the fetch.


If your SqlConnection object has not been disposed or closed you can reuse it on your next SqlCommand


Yes you can. SqlConnection implements IDisposible, so wrap it in a using block.

Psuedocode:

try
{
    using (SqlConnection conn = new SqlConnection(ConnectionString))
    {
       conn.Open();
       SqlCommand comm = new SqlCommand(conn);
       comm.CommandText = "Select Col1, Col2 From Table1";  

       SqlCommand comm1 = new SqlCommand(conn);
       comm.CommentText = "Select Col1, Col2 From Table2";

       //Execute First Command Code

       //Execute Second Command Code

    } //Connection will be closed and disposed
}
catch (Exception e)
{
    //Handle e - Really want to handle specific types of exceptions, like SqlExceptions etc.
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号