Jeff
Jeff

Reputation: 2313

Connecting to a database without explicitly openning a connection

I was helping a friend who is still in college with her business homework. The class teaches VB.NET and ADO.NET (really poorly of course). I only have brief experience with ADO.NET via a legacy application I support at work.

The page she was trying to implement was very simple: A form with inputs for username, password and a submit button. There were some functionality issues, but while looking through the code, I noticed something strange. Here is the code she used at the top of the page to set up the connection

Public Shared Con As New SqlConnection("Data Source = asdfa; Initial Catalog= asdf; Persist Security Info = True; User ID= dfasdf; Password = asdf")
Public Shared strSQLStatement As String
Public Shared strSQLStatementCmd As String
Public Shared daActivity As New SqlDataAdapter(strSQLStatement, Con)
Public Shared dsActivity As New DataSet

I did not see anything to the sound of con.open() as I have expected. From my knowledge, ADO.NET requires such a command to initially establish a connection. I questioned her about this and she mentioned that she has never used an open() command to establish a connection in any of her other homeworks, which she received full credit for. Is there something in this code that automagically opens the connection for me?

Maybe my understanding of ADO.NET is construed. Please correct me if I'm wrong, but the language is purely used to connecting to databases and is done so in this fashion

Set up connection string
Open connection
Create sql strings, such as command = "select * from table1"
Tell the open connection to run that sql
Close Connection

Does that seem about right? Help me help her.

Thanks

Upvotes: 1

Views: 168

Answers (2)

Talal Kh Bani Hani
Talal Kh Bani Hani

Reputation: 1

Dim MovingDA As New OleDbDataAdapter(sqlbyworknum, myConnection) MovingDA.Fill(MovingDT)

just you use new at declraing DA and pass sql and you connection it will be opend and run

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460360

SqlDataAdapter will automatically open and close the connection for you.

The Fill method retrieves rows from the data source using the SELECT statement specified by an associated SelectCommand property. The connection object associated with the SELECT statement must be valid, but it does not need to be open. If the connection is closed before Fill is called, it is opened to retrieve data, then closed. If the connection is open before Fill is called, it remains open.

http://msdn.microsoft.com/en-us/library/905keexk.aspx

Upvotes: 3

Related Questions