473,586 Members | 2,792 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

OOP question and correct class usage for connecting to DB

Jim
I'm writing an Invoicing Windows app but I'm writing it to make the code as
easy to maintain as possible. Basically, to get any records from my DB, I
use two classes: one that sets up the SQL statement, and another that makes
the connection (plus the class that contains the windows form). Now, is
this the best way to divide my tasks? And by using this structure, how would
I be able to update my dataset when I don't have direct access to the
dataadapter? Any suggestions on how this would be better organized would be
really appreciated.
This is how the code looks like:
--------------------
public class frm_AddNewProdu ct : System.Windows. Forms.Form

private void frm_AddNewProdu ct_Load(object sender, System.EventArg s e)

{ ...

DataAccess DataAccess = new DataAccess();

DS_Products = DataAccess.GetP roducts();

.... }

----------------------------

public class DataAccess

{ ....

public DataSet GetProducts()
{
string mySql = "Select itemid, Description, Quantity, Price from
products where producttype = 'P'";
DBConnection myConn = new DBConnection("S QLServer", mySql); //the
SQLServer parameter is not being used now
DataSet DS_MyProducts = new DataSet();
DS_MyProducts = myConn.Connecti on();
return DS_MyProducts;
}
}
----------------
public class DBConnection
{
public DataSet MyClientsDS;
public SqlDataAdapter MyDataAdapterCl ients;
string strThisConn, strThisQuery, strTable;
public DBConnection(st ring strDataBase, string strQuery)
{
strThisConn = strDataBase;
strThisQuery = strQuery;
strTable = strMainTable;
}
public DataSet Connection()
{
MyClientsDS = new DataSet();
SqlConnection SQLConn = new SqlConnection(" Data Source=localhos t;
Integrated Security=SSPI;" +
"Initial Catalog=invoici ng");
MyDataAdapterCl ients = new SqlDataAdapter (strThisQuery, SQLConn);
MyDataAdapterCl ients.Fill(MyCl ientsDS);
SQLConn.Close() ;
return MyClientsDS;
}
}

Thanks for your help.
Nov 15 '05 #1
2 1546
Hi Jim

Firstly, as you seem to be using SQLServer, I'd really recommend that you
use stored procedures.
If for only one reason, they will give you better maintainability .

I've taken the following approach in a Win32 app that proved to be quite
effective, especially in terms of reusability and maintainability :
// hide all data access/business logic inside static classes that represent
business entities
DataTable dt= Student.FetchBy FirstLast(txtFi rstName.Text,tx tLastName.Text) ;
if(dt.Rows.Coun t>0)
{
// .......
Inside this "Student" class I call a data access class (very similar to the
DAAB from MS).
Using this approach, with an atomic class, I can concentrate on the business
logic.

For updates, I pass the individual params to an "Update" on the respective
classes.
HTH

Cheers,

Simon Stewart
Johannesburg, South Africa
"Jim" <NA> wrote in message news:ec******** *****@TK2MSFTNG P10.phx.gbl...
I'm writing an Invoicing Windows app but I'm writing it to make the code as easy to maintain as possible. Basically, to get any records from my DB, I
use two classes: one that sets up the SQL statement, and another that makes the connection (plus the class that contains the windows form). Now, is
this the best way to divide my tasks? And by using this structure, how would I be able to update my dataset when I don't have direct access to the
dataadapter? Any suggestions on how this would be better organized would be really appreciated.
This is how the code looks like:
--------------------
public class frm_AddNewProdu ct : System.Windows. Forms.Form

private void frm_AddNewProdu ct_Load(object sender, System.EventArg s e)

{ ...

DataAccess DataAccess = new DataAccess();

DS_Products = DataAccess.GetP roducts();

... }

----------------------------

public class DataAccess

{ ....

public DataSet GetProducts()
{
string mySql = "Select itemid, Description, Quantity, Price from
products where producttype = 'P'";
DBConnection myConn = new DBConnection("S QLServer", mySql); //the
SQLServer parameter is not being used now
DataSet DS_MyProducts = new DataSet();
DS_MyProducts = myConn.Connecti on();
return DS_MyProducts;
}
}
----------------
public class DBConnection
{
public DataSet MyClientsDS;
public SqlDataAdapter MyDataAdapterCl ients;
string strThisConn, strThisQuery, strTable;
public DBConnection(st ring strDataBase, string strQuery)
{
strThisConn = strDataBase;
strThisQuery = strQuery;
strTable = strMainTable;
}
public DataSet Connection()
{
MyClientsDS = new DataSet();
SqlConnection SQLConn = new SqlConnection(" Data Source=localhos t;
Integrated Security=SSPI;" +
"Initial Catalog=invoici ng");
MyDataAdapterCl ients = new SqlDataAdapter (strThisQuery, SQLConn);
MyDataAdapterCl ients.Fill(MyCl ientsDS);
SQLConn.Close() ;
return MyClientsDS;
}
}

Thanks for your help.

Nov 15 '05 #2
Jim,
Its fine to seperate out your data access layer from the rest of your code
if you need or plan to have varying data sources (any exnterprise level
application would). What your doing here is a little off point though. A
data access layer tends to not only know how to connect to a database, but
know how to do the work as well (and know which tool in the shed to use).
Here, you are setting yourself up for one type of connection, a sql server
connection, so the only gain you have here is changing your database (not
really running multiple databases in parelles). Additionaly, your connection
method is always returning a DataSet. DataSets tend to be big and bulky and
should only be used when absolutly necessary. Most
of your application will likely benefit from a DataReader instead of a data
set (and btw, you don't have to close a connection if you didn't open it
outside of adapater). I am assuming from looking at this code, your client
classes know how to work with the data being returned in any way (be that a
data table, a data set, a reader, an xml flat file, whatever). So your not
getting much gain in terms of this class doing any real work. Pluss, your
creating a new object every time to want to make a call to your database
(this new class).
For maintainability , your on the right track. there isn't anything wrong
with wanting to have a data access layer that handles connections to various
database, the retriving of data and the modification of data. I would just
suggest you take a look at some design patterns that help you solve
particular problems in the data tier and build on that rather than having a
general knowledge of OOP and trying to solve problems that have been solved
many times over.
Wish i had a more specific answer for you, but without knowing more about
the app and what you already know regarding OOAD and patterns, this is the
best I can do.

-dec
"Jim" <NA> wrote in message news:ec******** *****@TK2MSFTNG P10.phx.gbl...
I'm writing an Invoicing Windows app but I'm writing it to make the code as easy to maintain as possible. Basically, to get any records from my DB, I
use two classes: one that sets up the SQL statement, and another that makes the connection (plus the class that contains the windows form). Now, is
this the best way to divide my tasks? And by using this structure, how would I be able to update my dataset when I don't have direct access to the
dataadapter? Any suggestions on how this would be better organized would be really appreciated.
This is how the code looks like:
--------------------
public class frm_AddNewProdu ct : System.Windows. Forms.Form

private void frm_AddNewProdu ct_Load(object sender, System.EventArg s e)

{ ...

DataAccess DataAccess = new DataAccess();

DS_Products = DataAccess.GetP roducts();

... }

----------------------------

public class DataAccess

{ ....

public DataSet GetProducts()
{
string mySql = "Select itemid, Description, Quantity, Price from
products where producttype = 'P'";
DBConnection myConn = new DBConnection("S QLServer", mySql); //the
SQLServer parameter is not being used now
DataSet DS_MyProducts = new DataSet();
DS_MyProducts = myConn.Connecti on();
return DS_MyProducts;
}
}
----------------
public class DBConnection
{
public DataSet MyClientsDS;
public SqlDataAdapter MyDataAdapterCl ients;
string strThisConn, strThisQuery, strTable;
public DBConnection(st ring strDataBase, string strQuery)
{
strThisConn = strDataBase;
strThisQuery = strQuery;
strTable = strMainTable;
}
public DataSet Connection()
{
MyClientsDS = new DataSet();
SqlConnection SQLConn = new SqlConnection(" Data Source=localhos t;
Integrated Security=SSPI;" +
"Initial Catalog=invoici ng");
MyDataAdapterCl ients = new SqlDataAdapter (strThisQuery, SQLConn);
MyDataAdapterCl ients.Fill(MyCl ientsDS);
SQLConn.Close() ;
return MyClientsDS;
}
}

Thanks for your help.

Nov 15 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2308
by: Peter Kleiweg | last post by:
I'm still new to Python. All my experience with OO programming is in a distant past with C++. Now I have written my first class in Python. The class behaves exactly as I want, but I would like to get comments about coding style. I'm especially unsure about how a class should be documented, what to put in, and where. When to use double quotes,...
14
2145
by: john.burton.email | last post by:
I've done some extensive searching and can't seem to find an answer to this - Is it correct to using "using" with templates, for example: using std::vector; Or do I need to specify the type too: using std::vector<int>; Both seem to "work" on the compiler I have and I can't find any documentation saying which is correct, or are both...
53
4542
by: Alf P. Steinbach | last post by:
So, I got the itch to write something more... I apologize for not doing more on the attempted "Correct C++ Tutorial" earlier, but there were reasons. This is an UNFINISHED and RAW document, and at the end there is even pure mindstorming text left in, but already I think it can be very useful. <url:...
23
2460
by: jm | last post by:
This works, but I don't know why. static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc),new Form1()); Application.Run(); }
1
2582
by: Tim T. | last post by:
I'm currently working on a report to forecast production for finished goods. The user can select one or more items to forecast. In addition, they may select one or more warehouses to view breakdowns for as well as one or more customers. Now, the report iterates through the selected items in the finished good listbox. For each item that it...
2
3273
by: Reny | last post by:
Hi, I want to develop an internet usage monitor program in vb.net and monitor the time the user spend on internet etc. Can any one give me a clue on how to code it? Reny
6
8609
by: Hunk | last post by:
Hi I have a question on usage of forward declarations of templates. While searching through this group , people suggested using forward declarations and typedefs for templates as // in myfile.h template<typename T,typename R> class some_class;
4
1894
by: Devon Null | last post by:
I have been exploring the concept of abstract classes and I was curious - If I do not define a base class as abstract, will it be instantiated (hope that is the right word) when a derived class is created? if ( answer == false ) { Would the idea of an abstract class simply be used to enforce integrity of the classes by disallowing the...
11
6236
by: Rafe | last post by:
Hi, I'm working within an application (making a lot of wrappers), but the application is not case sensitive. For example, Typing obj.name, obj.Name, or even object.naMe is all fine (as far as the app is concerned). The problem is, If someone makes a typo, they may get an unexpected error due accidentally calling the original attribute...
0
8199
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8336
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7950
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8212
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6606
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5710
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5389
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3835
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3863
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.