Best way to make central SqlConnection - c#

I have wondered what is the best way to make one central SqlConnection. So first thing when I started programming in C# was to put SqlConnection like this into each form I made:
public partial class form1 : Form
{
SqlConnection conn = new SqlConnection(
"Data Source=SERVER\\SQL;Initial Catalog=DataBase;User ID=user;Password=pass");
public form1 ()
{
InitializeComponent();
timer1.Start();
}
}
Now I would like to make one central connection and get rid of all of these codes in beggining of each form.
I thought that class would be best way to do that. So I wanted to ask you if there is another good method how to make that.
As I'm begginer, please excuse my level of description.
Thank you for your answer/comments/opinions.

The standard way to store SqlConnection information is to use a configuration file such as app.config or web.config. Alternatively, you may create your own configuration file.
After that, use ConfigurationManager.ConnectionStrings["YourConnectionStringName"].ConnectionString rather than the hardcoded connection settings

Using one "central" connection is highly discouraged as it breaks multiple patterns that ADO.NET implements. It is much easier to use a "central connection string" instead. If you want to use dynamic parameters, you might want to look into the "SqlConnectionStringBuilder" class.
ADO.NET is built around an "aquire late, release early" pattern for DB connections. Every other attempt will sooner or later cause massive problems (trust me on that, seen it many times: network errors/transaction errors/concurrency errors/multithreading errors...)
ADO.NET uses a "connection pool" for the actual physical connection to the database. So unless you use different connection strings for each conneciton, you should end up with one connection anyway. But since the "pool" manages that one, it will always be in a clean state when it is (re)opened.
Personally, I like to use something like this for my connection strings:
internal static class DataSource
{
private static string _ConnectionString;
public static string ConnectionString
{
get
{
if (_ConnectionString == null)
_ConnectionString = FunctionToDynamicallyCreateConnectionstring();
return _ConnectionString;
}
}
private static string FunctionToDynamicallyCreateConnectionstring()
{
SqlConnectionStringBuilder cb = new SqlConnectionStringBuilder();
// initialize cb's properties here...
return cb.ToString();
}
}
and later
SqlConnection connection = new SqlConnection(DataSource.ConnectionString);
This pattern will ensure that the exact same connection string is used thorughout my code and that the dynamic code still only runs once.
[EDIT] In most cases I avoid coding the entire connection string into the app.config file because some parameters might be mandatory for my code to work and should never be messed with. I create custom settings for "server" or "database" properties that I read and assign to the ConnectionStringBuilder...

Don't have one global connection because if it breaks (due to a network error) your app stops working. Also, you might have bugs with transactions accidentally left open or options set that other parts of your code do not expect.
Instead, store the connection string globally and create a fresh connection every time you need one. It is better to start fresh every time.
static class ConnectionFactory
{
public static SqlConnection Create() {
return new SqlConnection(GetConnectionStringSomehow());
}
}
Use it like this:
using (var conn = ConnectionFactory.Create()) {
//do something
}

You can look into the Data Access Pattern to handle all of the interfacing with sql.
This is usually the recommended approach, so multiple forms (or whatever the case may be) can access the same methods that retrieve and store data.
Here is a question about how to use it (with answers).

If you just want one globally accessible sql connection object then just look into static classes, as you can have a static class with a static constructor so everything can access it.
I would not do this, however if you are learning there is no harm in it, but statics/singletons are often used to have 1 instance of a component throughout an application.
// Simple static example
public static class DatabaseConnection
{
public static IDBConnection ActiveConnection {get; private set;}
static DatabaseConnection()
{
var myConnectionString = // get your connection string;
ActiveConnection = new SqlConnection(myConnectionString);
ActiveConnection.Connect(); // This is bad, really should be in a using
}
}
// Simple static usage
DatabaseConnection.ActiveConnection.ExecuteQuery(blah);
Problem is that you wont be controlling that resource, and it wont close the connection until the app closes which is bad practice, so you could improve on this slightly while still keeping your globally accessible functionality.
// Better static example using actions
public static class DatabaseConnection
{
private static string connectionString;
public static void OpenConnectionAnd(Action<Connection> actionToDo)
{
using(var connection = new SqlConnection(this.connectionString))
{
connection.Connect();
actionToDo.Invoke(connection);
connection.Disconnect();
}
}
static DatabaseConnection()
{
this.connectionString = // get your connection string;
}
}
// Better usage example
DatabaseConnection.OpenConnectionAnd(x => x.Execute(blah));
Syntax may not be 100% right as i'm just writing the above off top of my head, but should be close enough to be useful.

Related

C# using SQL Connection object for timer function

I'm creating an winforms application.
In which one form is made transparent, This form is used to show some popup message boxes, using a timer this form queries database in each seconds.
Currently I'm using database connection inside using method (here postgres Data Base).
Method 1
namespace MyApplication
{
public partial class frmCheckStatus: Form
{
private void timerCheckStatus_Tick(object sender, EventArgs e)
{
using (NpgsqlConnection conn = new NpgsqlConnection("My Connection String"))
{
conn.Open();
//Database queries
//Show popup message
conn.Close();//Forsing to close
}
}
}
}
so in each seconds this connection object is created and disposed.
Note : I'm not using this object for any other purpose or inside any forms or methods.
Is it good to create and use a single connection object global to this class, and use inside timer tick function?, and dispose on form close event
Method 2
namespace MyApplication
{
public partial class frmCheckStatus: Form
{
Private NpgsqlConnection conn = new NpgsqlConnection("My Connection String");
private void timerCheckStatus_Tick(object sender, EventArgs e)
{
//Here use conn object for queries.
conn.Open();
//Database queries
//Show popup message
conn.Close();//Forsing to close
}
private void frmCheckStatus_FormClosing(object sender, FormClosingEventArgs e)
{
conn.Dispose();
}
}
}
Which will be better?, considering memory, resource usage, execution time etc. Please give proper reason for your choice of method.
Looking at the documentation for your connection class (Here), it would appear that this supports connection pooling. This will mean that connections to the same endpoint (same connection string) will reuse existing connections rather than incurring the overhead of creating new ones.
Im not familiar with your particular connection, but if the behaviour is anything like SQLConnection class for ADO.net, repeatedly creating a new connection to the same connection string should not be particularly expensive (computationally).
As an aside, i would wrap your connection logic in try / finally to ensure it gets closed in the event of an application exception.
I can't see any advantage to instantiating a new connection every time you run a new query. I know it's done often in code, but there is overhead associated with it, however small. If you're running multiple queries from the start of the program to the end of the program, I think you should re-use the existing connection object.
If your goal is to make the connection "disappear" from the server (which I wouldn't generally worry about if this program runs on one machine -- if it runs on dozens, that's another story -- look up PgBounce), then that should be just as easily accomplished by turning connection pooling off, and then the Close() method would take care of it.
You kind of asked for pros and cons, and while it's not necessarily harmful to instantiate the connection within the loop, I can't imagine how it could be better.
For what it's worth, you may want to consider carrying the connection as a property (preferably outside of the form class, since you may want to eventually use it elsewhere). Something like this:
private NpgsqlConnection _PgConnection;
public NpgsqlConnection PgConnection
{
get
{
if (_PgConnection == null)
{
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.Host = "hostname.whatever.com";
sb.Port = 5432;
sb.UserName = "scott";
sb.Password = "tiger";
sb.Database = "postgres";
sb.Pooling = true;
_PgConnection = new NpgsqlConnection(sb.ToString());
}
if (!_PgConnection.State.Equals(ConnectionState.Open))
_PgConnection.Open();
return _PgConnection;
}
set { _PgConnection = value; }
}
Then, within your form (or wherever you execute your SQL), you can just call the property:
NpgSqlCommand cmd = new NpgSqlCommand("select 1", Database.PgConnection);
...
Database.PgConnection.Close();
And you don't need to worry if the connection is open or closed, or if it's even been created yet.
The only open question would be if you want that connection to actually disappear on the server, which would be changed by altering the Pooled property.

Linq to Sql: Change Database for each connection

I'm working on an ASP.NET MVC application which uses Linq to SQL to connect to one of about 2000 databases. We've noticed in our profiling tools that the application spends a lot of time making connections to the databases, and I suspect this is partly due to connection pool fragmentation as described here: http://msdn.microsoft.com/en-us/library/8xx3tyca(v=vs.110).aspx
Many Internet service providers host several Web sites on a single
server. They may use a single database to confirm a Forms
authentication login and then open a connection to a specific database
for that user or group of users. The connection to the authentication
database is pooled and used by everyone. However, there is a separate
pool of connections to each database, which increase the number of
connections to the server.
There is a relatively simple way to avoid this
side effect without compromising security when you connect to SQL
Server. Instead of connecting to a separate database for each user or
group, connect to the same database on the server and then execute the
Transact-SQL USE statement to change to the desired database.
I am trying to implement this solution in Linq to Sql so we have fewer open connections, and so there is more likely to be a connection available in the pool when we need one. To do that I need to change the database each time Linq to Sql attempts to run a query. Is there any way to accomplish this without refactoring the entire application? Currently we just create a single data context per request, and that data context may open and close many connections. Each time it opens the connection, I'd need to tell it which database to use.
My current solution is more or less like this one - it wraps a SqlConnection object inside a class that inherits from DbConnection. This allows me to override the Open() method and change the database whenever a connection is opened. It works OK for most scenarios, but in a request that makes many updates, I get this error:
System.InvalidOperationException: Transaction does not match
connection
My thought was that I would then wrap a DbTransaction object in a similar way to what I did with SqlConnection, and ensure that its connection property would point back to the wrapped connection object. That fixed the error above, but introduced a new one where a DbCommand was unable to cast my wrapped connection to a SqlConnection object. So then I wrapped DbCommand too, and now I get new and exciting errors about the transaction of the DbCommand object being uninitialized.
In short, I feel like I'm chasing specific errors rather than really understanding what's going on in-depth. Am I on the right track with this wrapping strategy, or is there a better solution I'm missing?
Here are the more interesting parts of my three wrapper classes:
public class ScaledSqlConnection : DbConnection
{
private string _dbName;
private SqlConnection _sc;
public override void Open()
{
//open the connection, change the database to the one that was passed in
_sc.Open();
if (this._dbName != null)
this.ChangeDatabase(this._dbName);
}
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
return new ScaledSqlTransaction(this, _sc.BeginTransaction(isolationLevel));
}
protected override DbCommand CreateDbCommand()
{
return new ScaledSqlCommand(_sc.CreateCommand(), this);
}
}
public class ScaledSqlTransaction : DbTransaction
{
private SqlTransaction _sqlTransaction = null;
private ScaledSqlConnection _conn = null;
protected override DbConnection DbConnection
{
get { return _conn; }
}
}
public class ScaledSqlCommand : DbCommand
{
private SqlCommand _cmd;
private ScaledSqlConnection _conn;
private ScaledSqlTransaction _transaction;
public ScaledSqlCommand(SqlCommand cmd, ScaledSqlConnection conn)
{
this._cmd = cmd;
this._conn = conn;
}
protected override DbConnection DbConnection
{
get
{
return _conn;
}
set
{
if (value is ScaledSqlConnection)
_conn = (ScaledSqlConnection)value;
else
throw new Exception("Only ScaledSqlConnections can be connections here.");
}
}
protected override DbTransaction DbTransaction
{
get
{
if (_transaction == null && _cmd.Transaction != null)
_transaction = new ScaledSqlTransaction(this._conn, _cmd.Transaction);
return _transaction;
}
set
{
if (value == null)
{
_transaction = null;
_cmd.Transaction = null;
}
else
{
if (value is ScaledSqlTransaction)
_transaction = (ScaledSqlTransaction)value;
else
throw new Exception("Don't set the transaction of a ScaledDbCommand with " + value.ToString());
}
}
}
}
}
I don't think that's going to work off a single shared connection.
LINQ to SQL works best with Unit of Work type connections - create your connection, do your atomically grouped work and close the connection as quickly as possible and reopen for the next task. If you do that then passing in a connection string (or using custom constructor that only passes a tablename) is pretty straight forward.
If factoring your application is a problem, you could use a getter to manipulate the cached DataContext 'instance' and instead create a new instance each time you request it instead of using the cached/shared instance and inject the connection string in the Getter.
But - I'm pretty sure this will not help with your pooling issue though. The SQL Server driver caches connections based on different connection string values - since the values are still changing you're right back to having lots of connections active in the connection string cache, which likely will result in lots of cache misses and therefore slow connections.
I think I figured out a solution that works for my situation. Rather than wrapping SqlConnection and overriding Open() to change databases, I'm passing the DBContext a new SqlConnection and subscribing to the connection's StateChanged event. When the state changes, I check to see if the connection has just been opened. If so, I call SqlConnection.ChangeDatabase() to point it to the correct database. I tested this solution and it seems to work - I see only one connection pool for all the databases rather than one pool for each db that has been accessed.
I realize this isn't the ideal solution in an ideal application, but for how this application is structured I think it should make a decent improvement for relatively little cost.
I think, that the best way is making UnitOfWork pattern with Repository pattern to work with Entity Framework. Entity Framework has FirstAsync, FirstOrDefaultAsync, this helped me to fix the same bug.
https://msdn.microsoft.com/en-us/data/jj819165.aspx

What are the possible issues of using single static instance of the de EnterpriseLibrary Database class for a DataLayer library?

I am doing a refactoring of many projects and I want to group together all the methods that access the database into a DataLayer library (instead of each proyect having its own class that access the database)
This is the approach that I am doing right now
private static Database DB = null ;
private static EventLog LOG = null ;
public static void Initialize()
{
string logName;
if (LOG == null)
{
logName = "DataLayer";
LOG = new EventLog();
if (!EventLog.Exists(logName))
{
//can fail because lack of permissions or other errors
try
{
EventLog.CreateEventSource(logName, logName);
}
catch (Exception)
{
}
}
LOG.Source = logName;
}
if (DB == null)
{
DB = DatabaseFactory.CreateDatabase("Name");
}
}
public static DataSet GetInfoFromDB(String param1, bool automatic)
{
DataSet resp;
DbCommand dbCommand;
object[] pars;
resp = null;
dbCommand = null ;
try
{
//prepare the parameters
pars = new object[2];
pars[0] = param1;
pars[1] = automatic;
dbCommand = DB.GetStoredProcCommand("StoredProcedureName", pars);
dbCommand.CommandTimeout = 1200;
resp = DB.ExecuteDataSet(dbCommand);
}
catch (Exception ex)
{
LOG.WriteEntry(string.Format("Error al ejecutar el StoredProcedure \"GetInfoFromDB\" {0}", ex.Message), EventLogEntryType.Error, 2004);
}
finally
{
if (dbCommand!= null)
{
dbCommand.Dispose();
}
}
return resp;
}
What are the posible issues of using single static instance of the de EnterpriseLibrary Database class for a DataLayer library ?
By issues I mean leaked connections, or if one mehod can somehow affect the others when multiple process start calling those methods or anyother
I would usually solve this by trial an error but I want to have an answer based on concepts and techinical/official information
ADDED
The main goal of the DataLayer and the refactor that I am planning is to take all the DB utility/common methods like GetAllParameters and many others that are replicated over and over on each project to avoid having to mantain and test them in every single project.
What I want is a unique method GetAllParameters that is called/reused in all the other projects
Therefore all the Common methods that can be used by many projects and are not part of a certain bussiness logic will be placed in DataLayer.Common like DataLayer.Common.GetAllParameters
And each logic that is specific for certiain funcionality will go inside its own DataLayer.BusinessLogicA.GetSpecificInfo
Is important to mention that this DataLayer will be used from projects like this
Website-->WebService-->BusinessLogic-->Datalayer
Winservice-->Datalayer
Winform-->Datalayer
By all your projects I assume all the projects in the same solution, its mad to mix DB access from different solutions in the same place, unless you are a DB/.Net guru.
1) you lose parallel access to the DB, depending on your project it might not be a problem, if it's a web project don't do it as all the calls to the server will clog up.
2) with the proposed approach you will mix business logic in each project and in the data access this is bad, makes it difficult to maintain, try to look into Entity Framework and other libraries to automate the access to the DB
3) Use the Unity from Enterprise Library to inject the DB context into each project, it will make it much more testable, I wont go into details as there are hundreds of examples on the WEB, but it might be the solution to why you are doing the refactoring.
It all sums up to probably its a bad decision to do it and it all depends on why you are doing it.
[Edit]
What you want is an extension method like the System.Linq library to do this you need to create a static class that implements a static method with the first parameter equal to this Database DB
public static MyClass
{
public static DataSet GetAllParameters(this DataBase DB, int someParam, ...)
{
<your DB function to get them>
}
}
Then tu use it you just add a using MyClass and in any DB object do var dataSet = DB.GetAllParameters(someParam, ...)
this will have a performance hit and if you pass the wrong DB it will blow up but its the fast way to do it, I strongly recommend you look into the IOC option with Automated DAL generator this will change the DataBase object to some specific table object and that make lots of verifications on compile time that this solution does not do.
Its ok to have your logger as a static class, but not for the conennection to the database.
Its recomended that you use using statement instead of a static function so it will be disposed automatically after its been used.
See this: Is the database connection in this class "reusable"?
This practice avoids having memory leaks,
Anytime you make a class static, you make it harder to test. Specifically you can't run it through a framework like Moq. That alone is reason enough to make it instanced.
As stated by Pedro.The.Kid in his answer, Injecting with UnityContainer (which would imply an interface to be implemented by your data access object) will go a long way toward making this a well managed object.
I would suggest to use a IOC container and let the container to handle the lifecycle of your DataClass you can use any container you want, if you want to follow the microsoft libraries then use Unity which is part of the enterprise library.
you can try to use Singletons or transients test them and see what would you prefer.
you can use something like this in you composite root:
public static void Register(IUnityContainer container)
{
container
.RegisterType<Database>(
new ContainerControlledLifetimeManager(),
new InjectionFactory(c => DatabaseFactory.CreateDatabase("Name")));
}
take a look to this answer for a more detailed explanation.

C# database wrapper design

I am designing a database wrapper for C#.
Below are the two options I have:
Option A:
class DBWrapper:IDisposable
{
private SqlConnection sqlConn;
public DBWrapper()
{
sqlConn = new SqlConnection("my connection string");
sqlConn.Open();
}
public DataTable RunQuery(string Sql)
{
implementation......
}
public Dispose()
{
if(sqlConn != null)
sqlConn.Close();
}
}
Option B:
class DBWrapper
{
public DBWrapper()
{
}
public DataTable RunQuery(string Sql)
{
SqlConnection sqlConn = new SqlConnection("my connection string");
.....implementation......
sqlConn.Close();
}
}
For option A connection is opened when class is instantiated. So no matter how many times the caller calls RunQuery the connection is always ready. But If the application instantiates DBWrapper early in the application, the connection will be just opened and doing nothing until the application is finished. Also, it could have many DBWrapper instantiated during the execution. So, it's kinda wasting resources.
For option B it doesn't have the problem option A has, but the a new connection has to be opened and closed everytime the caller calls RunQuery. I am not sure how much it will hurt the performance.
Please share your expertise. Thank you for reading.
For performance reasons, you'll definitely not want to go with Option B (at least in the cases I experienced.)
Let me suggest Option C:
class DBWrapper:IDisposable {
private SqlConnection sqlConn;
public void EnsureConnectionIsOpen()
{
if (sqlConn == null)
{
sqlConn = new SqlConnection("my connection string");
sqlConn.Open();
}
}
public DataTable RunQuery(string Sql)
{
EnsureConnectionIsOpen();
implementation......
}
public Dispose()
{
if(sqlConn != null)
sqlConn.Close();
}
}
You might consider using the singleton pattern to make sure there is only one instance of your DBWrapper.
A few comments worth considering:
In the approach where you manage a (perhaps) long-lived connection, it is important to check whether the connection is open before running a query. I've run into issues before where NETCF closed unused connections after a while.
In the approach where you open a new connection per-query, ensure that your connection, commands, and (if used) data readers are all properly wrapped in using statements or try/finally+dispose() blocks to free up connections and locks.
Happy coding!
Garbage collector is triggered under rather complex conditions but basically it is invoked when memory exceeds some limit, it is invoked periodically as well but the period is not constant. You never can be sure when exactly garbage collector disposes and consequently (in another run) destroys the object. One thing you can be sure is the fact that garbage collector will never dispose and destroy the object that still has references. For example object that is referenced via static variables on the class neither will be disposed nor destroyed.
Option B is more transactional, which has its advantages. ADO.NET uses implicit connection pooling, so you do not have to worry about creating new instances of SqlConnection frequently.
You should consider whether you are using a connected or disconnected data model; as the second approach lends itself better to a disconnected model.
But as i've said above, connection pooling means that it makes virtually no difference in practical terms.
You could have an option C where the database is opened on request in RunQuery (if it is not open) and closed on disposed (when it was opened). That way the database is only opened when really needed and will be opened only once.
So in pseudo code:
class DBWrapper
{
public DBWrapper()
{
}
SqlConnection sqlConn = null;
public DataTable RunQuery(string Sql)
{
if(sqlConn == null) sqlConn = new SqlConnection("my connection string");
.....implementation......
}
public Dispose()
{
if(sqlConn != null)
sqlConn.Close();
}
}
Also mind that the moment Dispose is called is not always directly after the object is not needed anymore (for example a function variable after the function is used). As far as I know it will be executed when the garbage collector collects the object (which is not directly). But I am not totally sure about this. This behaviour might also differ between web and non web application.

Access to SQL DB in multithread server app

In my server application I want to use DB (SQL Server) but I am quite unsure of the best method. There are clients whose requests comes to threadpool and so their processing is async. Every request usually needs to read or write to DB, so I was thinking about static method which would create connection, execute the query and return the result. I'm only afraid whether opening and closing connection is not too slow and whether some connection limit could not be reached? Is this good approach?
IMHO the best is to rely on the ADO.NET connection pooling mechanism and don't try to handle database connections manually. Write your data access methods like this:
public void SomeMethod()
{
using (var connection = new SqlConnection(connectionString))
using (var command = connection.CreateCommand())
{
connection.Open();
command.CommandText = "SELECT Field1 FROM Table1";
using (var reader = command.ExecuteReader())
{
while(reader.Read())
{
// do something with the results
}
}
}
}
Then you can call this method from wherever you like, make it static, call it from threads whatever. Remember that calling Dispose on the connection won't actually close it. It will return it to the connection pool so that it can be reused.
Surprised that no one mentioned connection pooling. If you think you are going to have a large number of requests, why not just setup a pool with a min pool size set to say 25 (arbitrary number here, do not shoot) and max pool size set to say 200.
This will decrease the number of connection attempts and make sure that if you are not leaking connection handles (something that you should take explicit care to not let happen), you will always have a connection waiting for you.
Reference article on connection pooling: http://msdn.microsoft.com/en-us/library/8xx3tyca.aspx
Another side note, why the need to have the connection string in the code? Set it in the web.config or app.config for the sake of maintainability. I had to "fix" code that did such things and I always swore copiously at the programmer responsible for such things.
I have had exactly the same problem like you. Had huge app that i started making multithreaded. Benefit over having one connection open and being reused is that you can ask DB multiple times for data as new connection is spawned on request (no need to wait for other threads to finish getting data), and if for example you loose connection to sql (and it can happen when network goes down for a second or two) you will have to always check if connection is open before submitting query anyway.
This is my code for getting Database rows in MS SQL but other stuff should be done exactly the same way. Keep in mind that the sqlConnectOneTime(string varSqlConnectionDetails) has a flaw of returning null when there's no connection so it needs some modifications for your needs or the query will fail if sql fails to establish connection. You just need to add proper code handling there :-) Hope it will be useful for you :-)
public const string sqlDataConnectionDetails = "Data Source=SQLSERVER\\SQLEXPRESS;Initial Cata....";
public static string sqlGetDatabaseRows(string varDefinedConnection) {
string varRows = "";
const string preparedCommand = #"
SELECT SUM(row_count) AS 'Rows'
FROM sys.dm_db_partition_stats
WHERE index_id IN (0,1)
AND OBJECTPROPERTY([object_id], 'IsMsShipped') = 0;";
using (var varConnection = Locale.sqlConnectOneTime(varDefinedConnection))
using (var sqlQuery = new SqlCommand(preparedCommand, varConnection))
using (var sqlQueryResult = sqlQuery.ExecuteReader())
while (sqlQueryResult.Read()) {
varRows = sqlQueryResult["Rows"].ToString();
}
return varRows;
}
public static SqlConnection sqlConnectOneTime(string varSqlConnectionDetails) {
SqlConnection sqlConnection = new SqlConnection(varSqlConnectionDetails);
try {
sqlConnection.Open();
} catch (Exception e) {
MessageBox.Show("Błąd połączenia z serwerem SQL." + Environment.NewLine + Environment.NewLine + "Błąd: " + Environment.NewLine + e, "Błąd połączenia");
}
if (sqlConnection.State == ConnectionState.Open) {
return sqlConnection;
}
return null;
}
Summary:
Defined one global variable with ConnectionDetails of your SQL Server
One global method to make connection (you need to handle the null in there)
Usage of using to dispose connection, sql query and everything when the method of reading/writing/updating is done.
The one thing that you haven't told us, that would be useful for giving you an answer that's appropriate for you is what level of load you're expecting your server application to be under.
For pretty much any answer to the above question though, the answer would be that you shouldn't worry about it. ADO.net/Sql Server provides connection pooling which removes some of the overhead of creating connections from each "var c = new SqlConnection(connectionString)" call.

Categories