Jason said:
Why would you need to have the connection global to the forms? Why not
encapsulate the connection in the data layer.
Sure, that would be good design.
And when you need to open a
connection, call the data layer which opens the connection and grabs the
data. From his post it seems to me that he is going to do all the database
logic (business rules) in the UI and I am trying to get him to create a data
layer and business layer. That way he does not need a global connection.
Again it's a totally seperate issue.
Here are 2 simple data layers, one using a persistent connection, one which
opens and closes a connection in each method. I would prefer the version
with the open connections in a client-server application. Heck, I even
prefer that version for web apps, you just have to Dispose the DAL object
after you use it each time.
Here is a DAL that keeps an open connection:
Public class DAL
Implements IDisposable
private con as SqlConnection
Public sub New()
con = new SqlConnection("...")
con.Open()
end sub
Public sub Dispose() implements IDisposable.Dispose
con.Close()
end sub
Public Sub CreateFoo(name as string)
dim cmd as new SqlCommand("insert into foo(name) values (@name)",con)
cmd.parameters.add(new SqlParameter("@name",name))
cmd.ExecuteNonQuery()
end sub
end class
Here is a DAL that opens and closes the connection each time:
Public class DAL
Public Sub CreateFoo(name as string)
dim con as new SqlConnection("...")
con.Open()
try
dim cmd as new SqlCommand("insert into foo(name) values (@name)",con)
cmd.parameters.add(new SqlParameter("@name",name))
cmd.ExecuteNonQuery()
finally
con.Close()
end try
end sub
end class