My database class

  • Thread starter Thread starter craigclister
  • Start date Start date
C

craigclister

I'm writing a small 'learning' app. It uses SQL Server.

I am trying to create a common class of database functions. So, am I
right in saying that it should be a static class? I've done that, but
then I can't declare a private class variable, because the class is
static...

internal static class Database
{
internal SqlConnection conn = new SqlConnection(); <---
Error...

internal static bool Connect()
{
try
{
conn.ConnectionString = "Data Source=localhost;
Integrated Security=SSPI; Initial Catalog=HomeShopper";
conn.Open();
return true;
}
catch(Exception e)
{.................................

How should I be doing this? I'd like to then be able to:

Common.Database.Connect();
 
I'm writing a small 'learning' app. It uses SQL Server.

I am trying to create a common class of database functions. So, am I
right in saying that it should be a static class? I've done that, but
then I can't declare a private class variable, because the class is
static...

internal static class Database
{
internal SqlConnection conn = new SqlConnection(); <---
Error...

internal static bool Connect()
{
try
{
conn.ConnectionString = "Data Source=localhost;
Integrated Security=SSPI; Initial Catalog=HomeShopper";
conn.Open();
return true;
}
catch(Exception e)
{.................................

How should I be doing this? I'd like to then be able to:

Common.Database.Connect();

Well, to do that you could make conn static (preferrably private, too)
- but maintaining a single static connection isn't a generally good
idea. It's better to open the connection when need it, and close it
immediately after you've used it, e.g. in a using statement.
 
Hi,

If the class is static then it should contani only static members. Not only
that but that code should not compile and should give you an error that a
static class can only contains static members.
 
It's better to open the connection when need it, and close it
immediately after you've used it, e.g. in a using statement.

Thanks (again) John. Can you give an example of the Using?
I guess you mean if I have a 'getData' type function which I pass an
SQL statement to, and returns a recordset, then the getData would open
the connection, do the query, return the data and close the connection?
 
Thanks (again) John. Can you give an example of the Using?

The using statement is something like:

using (SqlConnection conn = new SqlConnection())
{
// Use conn here
}
// conn has automatically been closed (Dispose has been called) even
// if an exception is thrown
I guess you mean if I have a 'getData' type function which I pass an
SQL statement to, and returns a recordset, then the getData would open
the connection, do the query, return the data and close the connection?

Exactly.
 
Back
Top