Creating a SqlConnection connection via connection string
Hi All, I have the following connection string:
Server=mssql01,3266;Database=ProductsDev;Trusted_Connection=True;
so I have the code:
string con_str = "Server=mssql01,3266;Database=ProductsDev;Trusted_Connection=True;";
using(var sqlConnection = new SqlConnection(con_str)) {
this.sqlConnection = sqlConnection; // store the object for the rest of the code to use.
}
I have this in a constructor, but when I use this sqlConnection object from another method where I am using a SqlCommand object to insert a row into a table it says it is closed, and I get the exception
The ConnectionString property has not been initialized.
Is the issue that I put the SqlConnection object in a using statement so its closing it?
but if if it is closing it, won't this.sqlConnection.open() reopen the connection to the db?
Thanks, I hope this makes sense.
3 Replies
not sure but have you tried manually opening and closing the connection where needed
Did you check
SqlCpnnection
in the docs: https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlconnection?view=dotnet-plat-ext-8.0#examples
The command is inside the using
statement of SqlConnection
. After the using statement the object is disposedSqlConnection Class (System.Data.SqlClient)
Represents a connection to a SQL Server database. This class cannot be inherited.
Post the full code its hard to know what you do, but it has probably something to do with you not opening the connection or disposing it.