473,788 Members | 3,101 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Database connection advice

Hi, I'm trying to modularize my database connections a little better and get
more out of my project with less code.

First check out this common dbOpen() function inside class clsDatabase. I
removed the try/catch part as it is not important for my question:

// This function opens a connection to the database.
public static SqlConnection dbOpen()
{
// Create a SqlConnection object and pass in our connection string
SqlConnection dbConn = new SqlConnection(@ "some connection string");
// Open our database connection
dbConn.Open();
}

Currently I call this function like so:
// Open our database connection
SqlConnection dbConn = new clsDatabase.dbO pen();
// do SOMETHING with the dbConn variable.
// some code that does something with the database using dbConn
variable.
// Done. Now close our database connection
clsDatabase.dbC lose(dbConn);

Now, I am stuck in an EventHandler (another part of this same page) where I
am trying to refresh a DataList with its values that looks like this:
protected void dlEmployeeDirec tory_EditComman d(object source,
DataListCommand EventArgs e)
{
// Start DataList editing mode
dlEmployeeDirec tory.EditItemIn dex = e.Item.ItemInde x;

// Refresh data
getEmployeeDire ctoryData(clsDa tabase.dbGetCon nection());
}

My question is, how can I use the database connection I was just working
with within this particular function? Do I have to create a new connection
using dbOpen and dbClose as I did in the code segment before this one? Note
that the only lines I added to the following "revised" code are dbOpen and
dbClose:
protected void dlEmployeeDirec tory_EditComman d(object source,
DataListCommand EventArgs e)
{
// Start DataList editing mode
dlEmployeeDirec tory.EditItemIn dex = e.Item.ItemInde x;
// Open our database connection
SqlConnection dbConn = new clsDatabase.dbO pen();
// Refresh data
getEmployeeDire ctoryData(clsDa tabase.dbGetCon nection());
clsDatabase.dbC lose(dbConn);
}

I'm trying to figure out a way to just open the connection once and always
be able to refer to it or pass it around instead of putting dbOpen and
dbClose in functions all over the page. I have no idea how to get the db
connection either within EventHandlers because they already come premade with
"(object source, DataListCommand EventArgs e) as the parameters to be passed
in. So I can't pass in the db connection and I don't know the code to just
"get" the last connection I was just working with.

Normaly I would just pass the database connection around from function to
function like so:

doSomething(dbC onn);
doSomethingElse (dbConn);

....but I can't even do that here because this is an EventHandler with
pregiven parameters.

Sorry, kinda new at C# still...any questions or comments are appreciated.
Thanks!
Nov 17 '05 #1
3 2478

"R Reyes" <RR****@discuss ions.microsoft. com> wrote in message
news:47******** *************** ***********@mic rosoft.com...
Hi, I'm trying to modularize my database connections a little better and
get
more out of my project with less code.

First check out this common dbOpen() function inside class clsDatabase. I
removed the try/catch part as it is not important for my question:

// This function opens a connection to the database.
public static SqlConnection dbOpen()
{
// Create a SqlConnection object and pass in our connection string
SqlConnection dbConn = new SqlConnection(@ "some connection
string");
// Open our database connection
dbConn.Open();
}


Ok that's good. Now anyplace you need a connection do this

using (SqlConnection con = clsDatabase.dbO pen())
{
//use the connection

}

The using block will close the connection at the end of the block.

David
Nov 17 '05 #2
R,

Depends what you do, if you use DataAdapters and Dataset, than you don't
even have to open and close your connections. The DataAdapter does that
intrensic.

(If you than do more fill action in one method, than it is a little bit
slower than with opens and closes around the fills)

I hope this helps,

Cor
Nov 17 '05 #3
Ok, I will try these out. Thanks for the quick replies you two! :)

"Cor Ligthert [MVP]" wrote:
R,

Depends what you do, if you use DataAdapters and Dataset, than you don't
even have to open and close your connections. The DataAdapter does that
intrensic.

(If you than do more fill action in one method, than it is a little bit
slower than with opens and closes around the fills)

I hope this helps,

Cor

Nov 17 '05 #4

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

Similar topics

4
2474
by: Macca | last post by:
Hi, I have an windows forms application that accesses a SQL database I have a few questions as to connecting to the database. This application will run 24 hours a day. It is a monitoring application and will store events that happen in the database (These events happen randomly without pattern, between 10-50 a day) . There are a number of situations where the database is accessed.
12
2122
by: Joe Abou Jaoude | last post by:
hi, I have a component that uses a database connection. In the finalizer I dispose the connection because I read in msdn the following: "A type must implement Finalize when it uses unmanaged resources such as file handles or database connections that must be released when the managed object that uses them is reclaimed."
13
2367
by: Robin Haswell | last post by:
Hey people I'm an experience PHP programmer who's been writing python for a couple of weeks now. I'm writing quite a large application which I've decided to break down in to lots of modules (replacement for PHP's include() statement). My problem is, in PHP if you open a database connection it's always in scope for the duration of the script. Even if you use an abstraction layer ($db = DB::connect(...)) you can `global $db` and bring...
2
1521
by: mesut demir | last post by:
Dear collegeaus, I would like to learn Visual Basic.NET and working with DATABASES. My intention is making some Windows programs using Database & Internet programs using Databaseses.(SQL) I'm a 3GL programmer.... Which and What book do you advice for start learning these stuffs? I have downloaded from Microsoft site:
35
4851
by: Terry Jolly | last post by:
Web Solution Goal: Have a global database connection Why: (There will be 30+ tables, represented by 30+ classes) I only want to reference the database connection once. I put the connection string in the web.config. I created a class with a static database connection and the class opens and closes the database.
3
2850
by: Bob Bedford | last post by:
hello I'm looking for some functions or objects allowing to select-insert-update-delete from any table in a mysql database without the need to create a new query every time. Example: selectdatas(array('field1','field2','fieldn'),array('table1','tablen'),array('left join,idy','inner join, idx')) then the function build the query, execute it and then return an object with
6
2243
by: John | last post by:
Hi I have a vb.net app that opens an access database runs several sql action queries on the tables and closes the db. This is done every few minutes. The problem is that sometimes I get an error 'ExecuteNonQuery requires an open and available Connection. The connection's current state is closed'. My question is; is there a situation where an app automatically closes the db connection causing this error and is there a way to prevent this?...
39
5870
by: alex | last post by:
I've converted a latin1 database I have to utf8. The process has been: # mysqldump -u root -p --default-character-set=latin1 -c --insert-ignore --skip-set-charset mydb mydb.sql # iconv -f ISO-8859-1 -t UTF-8 mydb.sql mydb_utf8.sql mysqlCREATE DATABASE mydb_utf8 CHARACTER SET utf8 COLLATE utf8_general_ci;
9
2337
by: Peter Duniho | last post by:
Is there a straightfoward API in .NET that allows for inspection of a database? That is, to look at the structure of the database, without knowing anything in advance about it? For example, retrieving a list of tables in the database. Doing a little browsing in MSDN, I see that the abstract representation of a database appears to be the DataSet class. I also see that I can use "data adapter" classes (e.g. OdbcDataAdapter) to connect a...
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
8993
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6749
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5535
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.