Hi,
We have an application where users must fill the same form several times,
creating each time a record in the database.
When checking the checkbox in this form means the last record.
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As
System.EventArgs) Handles Button1.Click
Dim connection As SqlConnection
etc ....
connectionstr = "Data Source=LAPTOP\SQLEXPRESS;Initial
Catalog=mydb;Integrated Security=True"
etc ....
comd.CommandText = "insert into [dbo].[mytable] (field1, field2, etc ...)
values(......);"
connection.Open()
comd.ExecuteNonQuery()
...
If CheckBox1.Checked Then
Server.Transfer("other.aspx")
end if
connection.Close()
end sub
My question is: do i have to close the connection like this or leaving it
open till the last record is inserted?
With other words: where to place the "connection.Close()"? Inside the "If
CheckBox1.Checked Then" or outside it?
Thanks for your advice.
Chris
Chris Walker - 11 Jul 2007 15:26 GMT
In general, the best practice for connections is "Open late, close early".
Since .net uses connection pooling, its actually less resource intensive to
open and close a connection several times, than it is to leave it open.
> Hi,
>
[quoted text clipped - 27 lines]
> Thanks for your advice.
> Chris
sloan - 11 Jul 2007 15:27 GMT
In a web environment, you should always open (as late as possible) and close
( as soon as possible ) your code.
You should at the very least, write some kind of wrapper class or
static(shared in vb.net) method to encapsulate the database call.
Your code below is ...... clanky at best.
Here is an example of a well layered application:
http://sholliday.spaces.live.com/Blog/cns!A68482B9628A842A!139.entry
> Hi,
>
[quoted text clipped - 27 lines]
> Thanks for your advice.
> Chris
Tony M - 11 Jul 2007 15:53 GMT
The link in article is broken
> In a web environment, you should always open (as late as possible) and
> close
[quoted text clipped - 41 lines]
>> Thanks for your advice.
>> Chris
sloan - 11 Jul 2007 16:38 GMT
Doohhh.
It's fixed.
> The link in article is broken
>
[quoted text clipped - 43 lines]
> >> Thanks for your advice.
> >> Chris
Chris - 11 Jul 2007 18:09 GMT
Thanks to all
> In a web environment, you should always open (as late as possible) and
> close
[quoted text clipped - 41 lines]
>> Thanks for your advice.
>> Chris