SQL connection management in ASP.Net

hi,
I have to create a small website in ASP.Net 2.0. I have question about 
working with SQL connections. What are the best practises? How and where to 
create and store a connection? I see a few possibilities:
- create, open/close a connection on each web page
- create a connection on login page and store it on Session
- how to create a connection? ie. SqlConnection = new SqlConnection or 
System.Data.Common.DbProviderFactory factory = 
System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
            System.Data.Common.DbConnection conn = factory.CreateConnection();

thx in advance
0
Utf
3/5/2010 8:45:01 AM
dotnet.framework.aspnet 1425 articles. 0 followers. Follow

2 Replies
1366 Views

Similar Articles

[PageSpeed] 23

"Chris" <Chris@discussions.microsoft.com> wrote in message 
news:C1682A3B-4BAB-4511-8D0E-897F5E3E8615@microsoft.com...
> hi,
> I have to create a small website in ASP.Net 2.0. I have question about
> working with SQL connections. What are the best practises? How and where 
> to
> create and store a connection? I see a few possibilities:
> - create, open/close a connection on each web page
> - create a connection on login page and store it on Session
> - how to create a connection? ie. SqlConnection = new SqlConnection or
> System.Data.Common.DbProviderFactory factory =
> System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
>            System.Data.Common.DbConnection conn = 
> factory.CreateConnection();
>
> thx in advance

You should have the connection string in web.config and have a class or 
something which exposes it.
You don't want to hold a connection open.
( google connection pooling ).

Your code above is doing some fancy factory class creation stuff by the look 
of it.
If you have a small project I wouldn't worry about that for now.
I'd keep it simple and have something like a class per table.
If you have no nulls then substitute datareader, if you do then google 
nullabledatareader.
I've hacked this code up a bit to simplify it, so it started as (old) live 
code then I probably broke it.

So the method will open up a connection, read a bunch of data, chuck it into 
a typed list, close the connection and return the list.
The class is (mostly) generated by an app I wrote, I can provide a copy.
using System;

using System.Data;

using System.Data.SqlClient;

using System.Web.Configuration;

using System.Collections.Generic;

using NullableReaders;

namespace Biz

{

public class People

{

public People()

{ }

private string _UserId;

private string _NetworkID;

private string _EmpNo;

private DateTime? _LeavingDate;



public string UserId

{

get

{

return _UserId;

}

set

{

_UserId = value;

}

}

public string NetworkID

{

get

{

return _NetworkID;

}

set

{

_NetworkID = value;

}

}

public string EmpNo

{

get

{

return _EmpNo;

}

set

{

_EmpNo = value;

}

public DateTime? LeavingDate

{

get

{

return _LeavingDate;

}

set

{

_LeavingDate = value;

}

}

public IList<People> GetPeople()

{

IList<People> People1 = new List<People>();

using (SqlConnection sqlConn = new SqlConnection(DB.connString))

{

sqlConn.Open();

SqlCommand sqlCmd = sqlConn.CreateCommand();

sqlCmd.CommandText = "select UserId, NetworkID, EmpNo,  LeavingDate from 
People";

using (NullableDataReader reader = new 
NullableDataReader(sqlCmd.ExecuteReader()))

{

while (reader.Read())

{

People c = new People();

c.UserId = reader.GetString("UserId");

c.NetworkID = reader.GetString("NetworkID");

c.EmpNo = reader.GetString("EmpNo");

c.LeavingDate = reader.GetNullableDateTime("LeavingDate");

People1.Add(c);

}

return People1;

}

}

}

}

}

0
Andy
3/5/2010 10:13:09 AM
"Chris" <Chris@discussions.microsoft.com> wrote in message 
news:C1682A3B-4BAB-4511-8D0E-897F5E3E8615@microsoft.com...

> - create a connection on login page and store it on Session

Under no circumstances do this! It's a guaranteed way of killing your web 
app's performance...
Create a connection every time you need to interface with the database and 
close it IMMEDIATELY you no longer need it.


> how to create a connection? ie. SqlConnection = new SqlConnection or
> System.Data.Common.DbProviderFactory factory =
> System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlClient");
> System.Data.Common.DbConnection conn = factory.CreateConnection();

Factory pattern is useful if you need to support more than one RDBMS. If you 
don't, and will never need to in the future, the factory pattern is 
unnecessary.


-- 
Mark Rae
ASP.NET MVP
http://www.markrae.net 

0
Mark
3/5/2010 3:36:27 PM
Reply:

Similar Artilces:

MS Outlook Fails after AT&T Connection
This is a multi-part message in MIME format. ------=_NextPart_000_0006_01CA1388.B3E7E6C0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable Experts, I use AT&T Global client for connecting to VPN. But the Microsoft = Outlook is not working for the VPN. Please let me know if there is any = proxy settings to be configured after connecting through AT&T Global = Client. Thanks in advance, Sivaswami ------=_NextPart_000_0006_01CA1388.B3E7E6C0 Content-Type: text/html; charset="iso-8859-1" Content-Transfer-Encoding: quoted-pri...

Business Contact Manager #38
Is this the correct News Group to mention this as I see no reference to this program in Outlook. microsoft.public.outlook.bcm --� Milly Staples [MVP - Outlook] Post all replies to the group to keep the discussion intact. Due to the (insert latest virus name here) virus, all mail sent to my personal account will be deleted without reading. After searching google.groups.com and finding no answer, tj asked: | Is this the correct News Group to mention this as I see | no reference to this program in Outlook. ...

Calling Dex Procedures from SQL
Is there any way to call dex procs from SQL or VB code? Jed There is an undocumented and unsupported method of calling Dex code from VBA. However, I know of no method of calling Dexterity from SQL. Please email me if you want an example, just remove the online. from the address below. David Musgrave [MSFT] Senior Development Consultant MBS Services - Asia Pacific Microsoft Business Solutions http://www.microsoft.com/BusinessSolutions mailto:dmusgrav@online.microsoft.com Any views contained within are my personal views and not necessarily Microsoft Business Solutions policy. This p...

is SQL 2000 architecture different SQL Server 2005 / 2008 architecture?
Hi I have a book "inside SQL Server 2000" by Kalen Delaney, which I have been told is a good book. I am going backwards... reading about the sql server architecture in chapter 3 of the book. As I'm reading... I was wondering is it different SQL Server 2000 vs SQL Server 2005/2008? Also where can I find a book/or link that can give me more details about the internals on architecture? Thank you norm (normanchan@gmail.com) writes: > Hi I have a book "inside SQL Server 2000" by Kalen Delaney, which I > have been told is a good book. I am g...

Moving customizations from SQL 2k to SQL 2k5 CRM
This may be a non-issue but I wanted to check to see if anyone has done this and ran into issues. I have the XML customization files from our previous install of CRM 3.0 with SQL 2k database. I now want to import and publish these same customizations to CRM 3.0 on SQL 2k5. Has anyone done this or can point me to documentation that tells about the success or issues for doing this? Thanks. On 7 Feb., 06:35, Chris Treanor <ChrisTrea...@discussions.microsoft.com> wrote: > This may be a non-issue but I wanted to check to see if anyone has done this > and ran into issues. > &...

Connection problems on SSAS for some projects
I am running on VS 2005 and Sql Server 2005 and trying to deploy my project to Analysis Server and I get the following message: A connection cannot be made. Ensure that the server is running. Additional information: No connection could be made because the target machine actively refused it. 127.0.0.1:2383 I created 2 project virtually identical. The only difference was that I created a new connection for the first project and then pointed at the existing connection for the 2nd project. The connection showing for both projects when I right-click the Adventure WorksDW...

CRM 3.0 Install Error with SQL Reporting Services and SQL 2005
Hi, Doing a CRM 3.0 Server installation. During the last page of the install wizard (or what I assume is the last page) when I goes through and does verification I get a red X next to SQL Reporting Services. The message I receive when I look at the details is: ***** The specified path is not a metabase path. Parameter name: path ***** Now SRS is installed and working. I put in the URL: http://<servername>/reportserver and every other variation on that I can find. Thoughts? Alan try http://servername/reports also assuming you did not use ssl... =======================...

Prior Year Trial Balance
When running a trial balance for a prior year, note the "net change" on a monthly basis is incorrect every month until December. The Net Change is the first line item of the following month, not the actual net change. -- JeannieC ---------------- This post is a suggestion for Microsoft, and Microsoft responds to the suggestions with the most votes. To vote for this suggestion, click the "I Agree" button in the message pane. If you do not see the button, follow this link to open the suggestion in the Microsoft Web-based Newsreader and then click "I Agree" ...

SQL 'for xml' and C# example??
I'm missing some piece of the puzzle. I'm using 'for xml' type queries from SQL2K - and now trying to change the front-end from ADO to C#, I can't quite figure it out.. It seems that I could use an XmlReader.. and somehow use that instead of a DataReader.. but that didn't work.. I tried using a DataReader and get the byte array - but that wasn't right. SQL returns formatted XML, I need to load that XML into an XmlDocument somehow without ANY molestation of that dom. Any ideas? Examples? Missing links???? thanks THANKS!! I've been looking for the answer to ...

sql summarizing help
Hi All, Given: table1 --------- id, cdate, weeksago, amount, typeid, timeclose 496, 2010-02-11, 0, 450, 3, 1 490, 2010-02-01, 1, 200, 4, 1 491, 2010-02-01, 1, 350, 2, 2 493, 2010-02-01, 1, 500, 5, 1 489, 2010-01-21, 3, 150, 2, 1 136, 2010-01-12, 4, 500, 3, 2 137, 2010-01-12, 4, 100, 3, 1 138, 2010-01-12, 4, 500, 2, 1 1. i'm trying to create a sql that will give me a summary resultset grouped by weeksago. 2. i want to sum the columns and get counts based on typeid. 3. avg of timeclose here's the sql i have: select weeksago, , (sum(timeClose)/(count(timeclo...

Eror connecting Reports MAnager
Hi all, i have been trying to install CRM 3.0 on a SBS installation with SQL 2000 installed and Sharepoint Services , and have the following problem: when I verify the report server the message is : servername/ReportServer - / -------------------------------------------------------------------------------- Microsoft SQL Server Reporting Services Versión 8.00.1038.00 but when attempt to go to the reports administrator can't connect : ERROR The connection has been finished: It is not possible to connect with the remote server. Thanks! ...

Update multivalue field in table from form with SQL
Access 2007 on Vista I am using a form to establish the variables for a report before it is created. One field on the underlying table is a multivalue field, and the form includes a multi-select combo box control. After selections are made and the OK button on the multi-select combo drop down is clicked, focus moves to the next control. I have discovered though, that the underlying table does not update immediately, but does so correctly when I close the form. This sequence does not deliver the proper report data, so I need a way to immediately update the underlying table (m...

Refer to SQL statements globally
I have two large SQL statements that I need to use across several forms, reports, etc. Rather than repeat them in each form, I'm trying to store and reference them globally. For example, I'd like to store strSQL1 and strSQL2 in a global module, so I can use either like this in a form: Random form: Me!lstResults.RowSource = strSQL1 Random report: Me.Report.RecordSource = strSQL2 Would I just store the SQL statements in a global module like: Public Function SQLSource() As String Dim strSQL1 As String Dim strSQL2 As String strSQL1 = "SELECT blah blah...

To SQL or not to SQL?
I have a very vertical product developed 100% in M/S Access. I developed it myself in 1993 in the initial release of Access and been with it ever since. It is currently very stable and running in Access 2003. My big question is how or even *if* we should move it to SQL. My customers are getting bigger all the time with more users. Typically our customers run one or two workstations generally never more than 5. Performance, however, is starting to slow with database sizes passing 500 meg. We also have a LOT of code behind forms so are bound tightly to the Access development environ...

E2K3: System Manager Public Folder Admin authentication dialogues
I am in the process of moving from an Exchange 2000 server to 2003. The 2003 server is up and running and part of my clients are on the new box. I used the PFMigrate tool to add replicas of the eixsting E2K public folders to the E2K3 server and it's working great. However, when I go to adminster the public folders (for replication settings, etc) in System Manager on the E2K3 server, it prompts me for authentication on each and every subfolder :-( My authentication is valid and works - but it always prompts me for it. If I Choose "Connect to:" and select the E2K server ins...

PostgreSQL or other SQL servers in RMS
Has anyone successfully implemented RMS with one of the free SQL servers? Theoretically, is there any reason why we have to use MS SQL Server 2000 for large databases? David "dh" <dh@discussions.microsoft.com> ha scritto nel messaggio news:1783A90D-AF3E-4D91-A445-0039D4E7E379@microsoft.com... > Has anyone successfully implemented RMS with one of the free SQL servers? > Theoretically, is there any reason why we have to use MS SQL Server 2000 > for > large databases? RMS has implemented only for MS SQL Server (2000/MSDE) and isn't possible to work with ano...

Issues Connecting to SQLServer
I=92m trying to use a DSN-less connection to a SQLSERVER DB and am experiencing problems. I can connect to all the tables I need and most of the views. However, one view is giving me problems. The view in question is a summary for use on a report =96 basically totaling up hours and dollars from a bunch of detail records =96 in an attempt to reduce the amount of data sent over the network. For some unknown reason, I can=92t set an index on the view, so whenever I try to link to it programmatically I get the =93Select Unique Record Identifier=94 dialog box. I don=92t want the end u...

Pass-Through Query / Multiple ODBC Connections
When creating a Pass-Through Query, is there a way to create two or more “ODBC Connect Str”s in the Property Sheet? ODBC;DSN=DMH_Hub;Description=DMH_Hub on MZPRODEDWADHOC;UID=mzbrosb;DATABASE=DMH_Hub;Trusted_Connection=Yes ODBC;DSN=DW1;Description=DW1 on MZPRODDW;UID=mzbrosb;Trusted_Connection=Yes Or better yet, is there a way to specify the connection of the query to automatically be whatever connection the linked tables are using? -- Tyro from Missouri Pass-through queries run on the server, not in Access, therefore unless the DBMS you're using on that server suppo...

writeback to SQL 2005
hello! I use excel 2007 iI open a connection agianst SQL server 2005 and choose a table. In my workbook i can now see this data from this table. if i change a value in some cell i wish to writeback to table in SQL server. Is this possible? It's possible through the use of VBA and ADO, but not simply using the data connection you've already established. Ross "CJ" <CJ@discussions.microsoft.com> wrote in message news:D54EC521-0DD5-4B3D-971B-4FF3394D6FA8@microsoft.com... > hello! I use excel 2007 > iI open a connection agianst SQL server 2005 and choose a table...

Option Explicit in .wsf and .asp files
Hi I have a number of .vbs files in the following format: C1.vbs: Option Explict Class clsC1 End Class I can include these files in a .wsf file like this: <package> <job> <script language="VBScript" src="C1.vbs"/> <script language="VBScript" src="C2.vbs"/> </job> </package> I also want to include the same files in an .asp file like this: <script language="VBScript" runat="SERVER" src="C1.vbs"></script> <script language="VBScr...

sql.request #2
Does anyone have a comprehensible guide on how to use it that a dolt like me can follow? Every time I try I get a #N/A. The only guide I can find is at http://www.bygsoftware.com/examples/zipfiles/UsingSqlRequest.zip but it's really hard to follow. From the MSDN Library: http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/office97/html/SEC41.asp Not sure how familiar you are with ODBC; but if you are getting #N/A as a result, it is usually because of problems either with the SQL syntax or the connection string. There are a few examples of connection strings in the re...

Can't connect to remote computer with Remote Assistance
When trying to access my mother’s computer using Remote Assistance I receive the following message: ”A Remote Assistance connection could not be established because the DNS name of the remote computer could not be resolved.” Both computers are running Windows XP SP3 and McAfee Anti-virus software. Both computers firewalls are set to allow Remote Assistance full access along with port 3389 enabled. I even tried to edit her IP address in the invitation, using the IP address from her internet provider, with the same results. She is e-mailing me the invitation as an attachme...

Attempting to connect to Microsoft Communications
Hello All, When we open Outlook 2003, we get a pop up "Communicating with Server- Microsoft Office Live meeting". Is there a way to get rid of this message popping up when opening Outlook. We are using Outlook 2003 version 11.5608.5606 Microsoft Add-in for Outlook verion 8.0.6362.114 Any suggestions. Thanks in Advance Vijay Disable the live meeting addin. -- Diane Poremsky [MVP - Outlook] Need Help with Common Tasks? http://www.outlook-tips.net/beginner/ Outlook 2007: http://www.slipstick.com/outlook/ol2007/ Outlook Tips by email: dailytips-subscribe-request@lists.outlo...

MSDE or SQL Personal or SQL Developer? or SQL Workstation?
Hi, which one is better for personal non-server computer? MSDE? SQL Personal? SQL Developer? SQL Workstation? Thank you. It depends on what edition of GP you are going to run. If you are going to use Professional, you need to go with SQL Server developer, assuming you are installing on a non-server OS. "ano" wrote: > Hi, which one is better for personal non-server computer? MSDE? SQL Personal? > SQL Developer? SQL Workstation? > Thank you. Is the function of SQL Developer the same as Enterprise edition? How about personal edition? Can it be used for GP Pro? Can dev...

Excel RoundUp in Transact-SQL
Last week I posted the following computation in Excel... roundup(roundup(rate * 500),4) - roundup(rate * 200,4) + polfee,2) ((6.108934 * (500000/1000)) - (200 * 6.108934) + 1311.51) = 3144.20 In SQL using round(num,4) = 3144.19 I've moded this to... round(num+0.0005,4) = 3144.20 This works most of the time but occasionally I'm still off from what Excel returns. I'm under 2% in my 342 calcs, so it's do-able and we'll explain if any client notes this that we've reduced their pmt by .01 cents. BUT, I'd still like a way to replicate Excel'...