.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
Gaurav Pal
Post New Web Links

close connection

Posted By:      Posted Date: October 04, 2010    Points: 0   Category :ASP.Net


I am using a adapted version of


Don't we need something like a closing-routine / close connection command after getting data from the database?

If yes: What is the correct closing command?


View Complete Post

More Related Resource Links

When establishing a connection with a SQL databse using a try catch Does the try catch close the dat

HI everyone,  I have read a lot about SQL and I am told always to close the connection to the database after you finish. But what happens when you use a try catch and an error oucurs that bypasses the close statement? Since the SQL is enclosed in the try catch you cannot close the connection. Does the try catch close the connection automaticaly?  If it needs to be closed how would you close it? CurtisAlways Lost in Code, Always mark answers as correct if they answer you question and solve your problem. This way others when searching for similar problems can find the answer faster.

SQL server connection - keep it opened all the time, or open/close on demand ?



I have a VB6 app that gets data from several devices and has to store it in a SQL server 2005 database.
It may have to store small amounts of data (a few KB at most) somewhere between 5 and 500 times per day.
My app only sends data to DB, doesn't read anything.

My question is what's better in this case:

a) the app opens a connection to DB at startup and closes it at exit, or
b) when data arrives, the app opens a connection, sends data, then closes the connection


Open vs Close Connection


Hi Guys,

I have a question related to  leave a SQL connection open or close it.

Here is the scenario...

I have an Intranet page that monitors a Robot, that webpage needs to be up 24hours/7days a week.

Robot sends information to a SQL database every couple of seconds or minutes depending on the work it performs.

My page has an AJAX Timer that triggers every 5 sec, in that page I have to query the database (simple SELECT - no more then 15 lines) and show my info in a gridview.

The question is: Should I open the connection and leave it open or should i open and close every 5 secs?


Connection Close, Data.CommandBehavior.CloseConnection


Please can you check the following code and tell me if I need to close the connection?

On the following Click Event, first loading SqlDataReader into DataTable and than calling ExportCSV Procedure (passing loaded Datatable)


Protected Sub ExportCSV(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExportOrders.Click
Dim dt As DataTable = New DataTable()

dt.Load(CoreAdmin_.ExportOrders)  '/// Calling SqlDataReader Code as below "ExportOrders()"

CoreAdmin_.ExportCSV(dt, "ExportOrders_" & FormatDateTime(Now(), DateFormat.ShortDate) & "") '/// Calling Public Shared Sub ExportCSV

dt.Dispose()  '/// <<<<<<  Do I need to Dispose it here ???????
end Sub


Public Shared Function ExportOrders() As SqlDataReader

Dim cn As New SqlConnection
cn = New SqlConnection(ConfigurationManager.ConnectionStrings("SiteConn").ConnectionString)
Dim cmd As New SqlCommand("sp_ExOrders", cn)
cmd.CommandType = Data.CommandType.StoredProcedure

Return cmd.ExecuteReader(Data.CommandBehavior.CloseConnection)
Catch e As Exception
Throw e

Close DB Connection upon application termination?


The reason this question came up, is because if I run my website application with a SQL Server data store, and I terminate the browser (terminating the session), I try to open up SSMS to edit the DB.  But I can't access the database because I believe there is still an open connection, even after application termination.

Is it recommended to close the database connection upon session/application closing?  Or am I way off on what I'm thinking could be the problem?

Thanks in advance. :)

need to close the connection.

  public static int UpdateLastLogin(string userName, string sessionID)

    if (userName == null)
      return 0;

    Database db = OmegaLoveSqlDataHelper.CreateConnection(ConnnectionString);
    DbCommand dbCommand = db.GetStoredProcCommand("prc_Profile_Update_LastLogin");

    SqlParameter parm1 = new SqlParameter("@UserName", SqlDbType.NVarChar);
    parm1.Direction = ParameterDirection.Input;
    parm1.Value = userName;
    parm1.Size = 50;

    SqlParameter parm2 = new SqlParameter("@SessionID", SqlDbType.NVarChar);
    parm2.Direction = ParameterDirection.Input;
    parm2.Value = sessionID;
    parm2.Size = 32;

    int retValue = db.ExecuteNonQuery(dbCommand);

    return retValue;


I need to check if connection is open then close



SQL Connection String

We can learn or know how can we connect the database from our .net. This will help for freshers or .NET beginners!

abstract away the source of the connection string using a class with a static property.

ASP.NET provides a configuration system we can use to keep our applications flexible at runtime. In this article we will examine some tips and best practices for using the configuration system for the best results.

The element of a web.config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work. The items inside appSettings are items that need to be configurable depending upon the environment, for instance, any database connection strings will change as you move your application from a testing and staging server into production.

Let's abstract away the source of the connection string using a class with a static property.

WebDev.WebServer.exe has encounted a problem and needs to close when trying to view page in browser


Hi, whenever I load an aspx page in vwde2008, I get the message in the subject of this post.  After I click Ok on that, I get a dialog box, Unable to Connect to the ASP.Net development center.  What can I do to troubleshoot?

I am using Windows XP SP3, vwde2008 with SP1, on a HP desktop.  Also using Office 2003 if that is relevant at all.

Thanks, Justin

connection string question from a newbie


when publishing  in the webmatrix dialogue it asks for "destination connection string" for my "database.mdf"

I was not sure what it was so I pasted this from my web.config file :

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\database.mdf;Integrated Security=True;User Instance=True

it all published ok, but wont run, so I guess it has somthing to do with this connection string or some kind of configuration issue.

My question is this, What should go in the field for "Destination connection string"

localhost is not set up to establish a connection on port 51624 with this computer


I'm trying to run asp.net locally, but getting the error

localhost is not set up to establish a connection on port 51624 with this computer

How can I fix it?

connection to SQL Server files (*.mdf) require SQL server express 2005 to function properly.


I dont have the SQL EXPRESS installed instead I have SQL Standard Edition.

 I have two SQL Server instances installed.

 1- UserLT (this is sql 2000)
2- UserLT\SQL2005 (this is SQL 2005 named instance)

But when i try to add a database to my VS website project I get the following error:

Connection to SQL Server files (*.mdf) require SQL server express 2005 to function properly. please verify the installation of the component or download from the URL: go.microsoft.com/fwlink/?linkId=4925

I went in Tools>Opetions>DataBase tools>Data Connection>Sql Server Instance Name (blank for default)

and changed the "SQLEXPRESS" to "USERLT\SQL2005".

But I still get the same error message. Any ideas how i can resolve this issue?

Unable to make connection to database?


Hy guys. I try to connect my database for so long so i wrote two type of codes. Let's discuse first on.

I have database called PhoneDirectory.

It have only one table named Residents.

I have button wiht ID="Button1".

I want when i click this button to see all of my residents. 

I want to see the result in DetailsView and to be able to edin, delete and add new resident.

First try with SqlDataSource so i wrote this:

<asp:SqlDataSource ID="Resident Details" runat="server" ProviderName="System.Data.SqlClient" ConnectionStrings="<%$ ConnectionStrings:ThisIsTheConnection%>" 
              SelectCommand = "SELECT * FROM Resident "

Need Oracle Data Provider .CS File for Oracle 10g Database connection !



I need a 'Wrapper.cs' file which takes care of the Database connection ( Oracle 10g) where

i can just call the method with my SQL Query


Gridview1.DataSource = SampleWrapper.ExecuteDatatable("THE SQL QUERY");


Plz Post the link if there is any open source !    

Intermittant error: "A connection attempt failed because the connected party did not properly respon



I'm having a doozy of a problem, and can't find a solution.  I have a WFC Web Service installed to a pair of servers, and accessed through a load balancer.  I am accessing the service from an ASP.NET client app, also via WCF.  The Client is not load balanced.

I'm getting an intermittant error:

(Inner Most Exception) System.Net.Sockets.SocketException:  A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond x.x.x.x:80

(Middle Exception) System.Net.WebException: Unable to connect to the remote server

(Outer Exception) System.ServiceModel.EndpointNotFoundException:  Could not connect to http://<MYSite>/<MYApp>/<MYService>.svc. TCP error code 10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond x.x.x.x:80.

I can reproduce this error with about 20% reliability if I execute the exact same page request on the client from 2 browsers at the same time.  When the problem occurs, the successful p

Modifying connection String in Web config using Install Wizard



Im trying to create a Web Deployment Project, the built in setup and deployment is very good in Visual Studio, i need to able to add an additional step in the setup to change the connection string in the Web config file. Ive seen a lot of articles on how to do this and in particular this http://weblogs.asp.net/scottgu/archive/2007/06/15/tip-trick-creating-packaged-asp-net-setup-programs-with-vs-2005.aspx#7162670 I am however stuck on the final part of this tutorial, im using the code Scott provided but have two errors,  heres part of my code where the errors are

using System;
using System.Configuration;
using System.Configuration.Install;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.DirectoryServices;

 void ConfigureDatabase(string targetSite, string targetVDir, string connectionString)
            // Retrieve "Friendly Site Name" from IIS for TargetSite
            DirectoryEntry entry = new DirectoryEntry("IIS://LocalHost/" + targetSit

About WAP and MSSQL Connection


Is it possible to create a wap having a mssql connection?

Can you give me some sample code? thanks

ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend