Tuesday, 10 September 2013

Good Coding Practice with Databases: One connection / query vs one connection / all queries

Good Coding Practice with Databases: One connection / query vs one
connection / all queries

So I am finding myself struggling which is the best practice. This is my
first time coding C# and first time coding anything in like a decade. Back
when I worked as a php / sql programmer, we usually frowned on the idea of
opening a new connection for every query, but the more I research this
question on google today, specifically with C# and sqlite, the more it
seems many recommend doing the polar opposite.
So, I was hoping the put this question out for some of you guys, who have
obviously been doing this a lot more than eye. Here is the general setup
of my database class:
class DatabaseController
{
static private SQLiteConnection _sqlconn;
static private string _uri;
public static SQLiteConnection Sqlconn
{
get { return DatabaseController._sqlconn; }
set { DatabaseController._sqlconn = value; }
}
public static string Uri
{
get { return DatabaseController._uri; }
set { DatabaseController._uri = value; }
}
}
The second class, which is the main Database class, which deals with
actually running queries and such. The reason I have the
DatabaseController class is because I can store the open connection handle
to the static member _sqlconn and so the connection is only ever opened
once, and Database objects simply use the same handle, even though the
program can and will create many Database objects.
But again, is this actually necessary? Should I simply be opening a new
connection within the main Database class, every time an object is
created? There was another site and thread I found that apparently, what
the .NET Framework does is even though you maintains a connection pool for
you, so even though you might be opening and disposing of several
connections, they aren't truly closed. Is this truly so, and does that
apply to both desktop and windows 8 apps?

No comments:

Post a Comment