Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DB Connection Question

Status
Not open for further replies.

James1981

Programmer
Nov 2, 2002
76
0
0
US
Hi there,

I want to encapsulate a db connection into a class and then have a static method within this class that returns an open connection to a database.

I want to know if the connection is closed properly, as the method returns the connection before the closed() command is called. Here is my code:

The method within the class:
Code:
public static SqlConnection cnn()
		{
			try
			{
				SqlConnection myConn = new SqlConnection(ConfigurationSettings.AppSettings["ConnectionString"]);
				myConn.Open();
				return myConn;
				myConn.Close();
			}
			catch
			{
				return null;
			}
		}

How i use this method:
Code:
   myCommand (sql, dataclass.cnn());


Does the method close the connection properly or shall i create an instance of my data class and call the appropriate method to close it?

Thanks,

James
 
James - can't answer directly what your problem may be, but the topic of opening connections, best places to put them, etc, has been heavily discussed here at tek-tips over the last year - several very good posts have been written - might want to do a fairly exhaustive search here and of course other sites. Someone may drop by to offer an input - this is the first time I have seen a connection approach such as yours.
 
as i can see you are using a SQL server most likely it is MSSQL server. here is some code that you can use to connect to it.
i dont remember the code for drawing the table

<%@ page language=&quot;VB&quot; aspcompat=true %>
<html>
<head>
<title>How to Connect to an SQL server</title>
</head>
<body>
<%
dim oConn
dim sConn
dim rs
dim oField
dim sCmd
'now i have declared all variables
oConn = server.createObject(&quot;ADODB.Connection&quot;)
'this creats the instance of an apartment threaded model on
'the server
sConn = &quot;Provider=MSDASQL.1;Presist Security info=False;UID=the name of your database user goes here;PWD=Password Goes here;Inital Catalogue=Database name goes here&quot;
oConn.open(sConn) 'i dont know about theorder of these vars, if this dosent work change this line of code to sConn.open(oConn)
sCmd = &quot;Your SQL Statement Goes here&quot;
oConn.execute(sCmd)
.............................................
What you do with your data after that is for you to decide. i dont remember the example but that gets you connected to an SQL server this example only works if you have setup the connection in your ODBC Connections.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top