473,396 Members | 1,998 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

A question about sql connection in C# code.

Hi all,

I am writing the C# code function that take 2 parameters and access
the data in the MS SQL database and return a SqlDataReader object. In
my funtion, a SQL connection is established and open the connnection
before reading the data. Everything seem to be fine, but once I add the
close() function to close the sql connection, error come out. So I
leave out the close() function in my function. My code is showing below

-------------------------------------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication3
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string found = "c553a15f-15bd-4081-bd5d-89cfa2cc0505";
int photoId = 3;

SqlDataReader answer = ReadQuantity(found, photoId);
while(answer.Read())
{
int photoQuantity = Convert.ToInt16(answer["Quantity"]);
Console.WriteLine("\t{0}", photoQuantity);
}
}

static SqlDataReader ReadQuantity(string cartId, int photoId)
{
SqlConnection thisConnection = new SqlConnection
(@"Data Source=(local);Integrated Security=SSPI;" +
"Initial Catalog=PhotoDB");
thisConnection.Open();
SqlCommand ReadQuantity = thisConnection.CreateCommand();
ReadQuantity.CommandText = "SELECT Quantity FROM ShoppingCart WHERE
CartID = '"+cartId+"' AND PhotoID = '"+photoId+"'";
SqlDataReader thisReader = ReadQuantity.ExecuteReader();
// thisConnection.Close();
return thisReader;
}

}
}

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

Could everyone tell me what happen to the sql connection if I don't
include the close function in my code. Would it close automatically
after timeout and would it be security threat???

Thanks for your time

Wing

Nov 17 '05 #1
3 1725
I think that DataReader is connection-oriented, meaning that you must
maintain the connection for the data to be returned. Basically a DataReader
returns on record at a time. This is different from a DataSet/DataAdapter
which loads all the records in memory.

"Wing" <li******@gmail.com> wrote in message
news:11**********************@z14g2000cwz.googlegr oups.com...
Hi all,

I am writing the C# code function that take 2 parameters and access
the data in the MS SQL database and return a SqlDataReader object. In
my funtion, a SQL connection is established and open the connnection
before reading the data. Everything seem to be fine, but once I add the
close() function to close the sql connection, error come out. So I
leave out the close() function in my function. My code is showing below

-------------------------------------------------------------------
using System;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApplication3
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
string found = "c553a15f-15bd-4081-bd5d-89cfa2cc0505";
int photoId = 3;

SqlDataReader answer = ReadQuantity(found, photoId);
while(answer.Read())
{
int photoQuantity = Convert.ToInt16(answer["Quantity"]);
Console.WriteLine("\t{0}", photoQuantity);
}
}

static SqlDataReader ReadQuantity(string cartId, int photoId)
{
SqlConnection thisConnection = new SqlConnection
(@"Data Source=(local);Integrated Security=SSPI;" +
"Initial Catalog=PhotoDB");
thisConnection.Open();
SqlCommand ReadQuantity = thisConnection.CreateCommand();
ReadQuantity.CommandText = "SELECT Quantity FROM ShoppingCart WHERE
CartID = '"+cartId+"' AND PhotoID = '"+photoId+"'";
SqlDataReader thisReader = ReadQuantity.ExecuteReader();
// thisConnection.Close();
return thisReader;
}

}
}

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

Could everyone tell me what happen to the sql connection if I don't
include the close function in my code. Would it close automatically
after timeout and would it be security threat???

Thanks for your time

Wing

Nov 17 '05 #2

"Wing" wrote...
I am writing the C# code function that take 2 parameters and access
the data in the MS SQL database and return a SqlDataReader object. In
my funtion, a SQL connection is established and open the connnection
before reading the data. Everything seem to be fine, but once I add the
close() function to close the sql connection, error come out. So I
leave out the close() function in my function. My code is showing below
You didn't close the Reader before you closed the Connection...

There are several different solutions to your problem, and it comes down to
what design you really want for your system. There are basically two
different approaches for how to deal with connections, readers, etc, which
can be combined into several different solutions.

1. Open, deal with the data, and close it as fast as you can.

2. Keep it open during the whole session

Both have advantages and drawbacks depending on what tasks the application
should do, but I'll try to sketch two basic examples on how you could deal
with it.

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

1.
static ArrayList ReadQuantity(string cartId, int photoId)
{

ArrayList quantities = new ArrayList();

SqlConnection thisConnection = new SqlConnection
(@"Data Source=(local);Integrated Security=SSPI;" +
"Initial Catalog=PhotoDB");
thisConnection.Open();
SqlCommand ReadQuantity = thisConnection.CreateCommand();
ReadQuantity.CommandText = "SELECT Quantity FROM ShoppingCart WHERE
CartID = '"+cartId+"' AND PhotoID = '"+photoId+"'";
SqlDataReader thisReader = ReadQuantity.ExecuteReader();

while(thisReader.Read())
{
quantities.Add(answer["Quantity"]);
}

thisReader.Close();
thisConnection.Close();
return quantities;
}

----------------------------------------------------
1 + 2.

In this scenario you open the connection beforehand, and can keep it open
the whole session. Note that you then pass the connection to the method.
(Not really Recommended!)

static ArrayList ReadQuantity(string cartId, int photoId, SqlConnection
con)
{

ArrayList quantities = new ArrayList();

SqlCommand ReadQuantity = thisConnection.CreateCommand();
ReadQuantity.CommandText = "SELECT Quantity FROM ShoppingCart WHERE
CartID = '"+cartId+"' AND PhotoID = '"+photoId+"'";
SqlDataReader thisReader = ReadQuantity.ExecuteReader();

while(thisReader.Read())
{
quantities.Add(answer["Quantity"]);
}

thisReader.Close();
return quantities;
}

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

Note that both examples deals with the actual data before returning.

Hmm, but I wonder if you really need a DataReader at all? Does the statement
really return more than one row, or could you suffice with using only the
ExecuteScalar method?
Could everyone tell me what happen to the sql connection
if I don't include the close function in my code. Would
it close automatically after timeout and would it be
security threat???


That is depending on many things, but it will logically not close, even if
it times out from the server, so it's good practice in all cases to close
the connection as soon as possible when you're done with it.

I wouldn't see it as a bigger "security threat" to keep it open than to just
open and close it, but rather a possible misuse of resources. If the number
of simultaneous connections are limited, an unnecessary open connection can
block out other users, or even yourself, if you keep opening connections,
but never close them.

// Bjorn A
Nov 17 '05 #3
Thanks very much for your suggestion, help and time. very appreciated!

What I want the function ReadQuantity to do is to return 2 values in
the particular row (of caurse I need to change the SELECT statemant) by
return the SqlDataReader object. Now your exmaple remind me that I can
assign the value in SqlDataReader object into array and return the
array instead, and I can close the connection which no longer need.

Thanks again.

Wing

Nov 17 '05 #4

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

Similar topics

3
by: Mudge | last post by:
Hi, My hosting provider only allows me to use 50 connections to my MySQL database that my Web site will use. I don't know what this 50 connections means exactly. Does this mean that only 50...
1
by: eScrewDotCom | last post by:
eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew...
8
by: eScrewDotCom | last post by:
eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is very funny. eScrew...
4
by: Utada P.W. SIU | last post by:
Dear All, My asp run smoothly before. But, now, I found the ASP page is not smoothly recently. Sometime if the ASP is requested to connect to Access, the page will prompt Microsoft OLE DB...
5
by: eScrewDotCom | last post by:
www.eScrew.com eScrew Welcome to eScrew! eScrew is eScrew and this is eScrew story. eScrew will tell you eScrew story if you promise eScrew to consider eScrew story as joke. eScrew story is...
4
by: 0to60 | last post by:
I have a question about socket programming in general. Exactly what happens behind the scenes when I one socket connects to a different socket in listen mode? Using the dotnet framework, I...
2
by: Ellen Manning | last post by:
Using A2K and adp. Is it necessary to open a connection (to SQL Server 2000) everytime you call a stored procedure or open a recordset? Or will opening a connection one time do, like at...
2
by: Tom | last post by:
1. I drag the sqlDataAdapter and sqlConnection from the tool bar to the web form. It creates automatically: protected System.Data.SqlClient.SqlDataAdapter sqlDataAdapter1; protected...
9
by: Alvin Bruney [MVP] | last post by:
with the using construct, exit from scope calls dispose on said object. But what happens in a connection pooling scenario? Is the run-time smart enough to realize that Object Pooling is being used...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...
0
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,...

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.