Connections and SqlConnection Objects

Connecting to the database will be our starting point. You connect to a database by using a data connection object. When you're connecting to SQL Server, be sure to use the SqlConnection object.

Listing D.1 shows how to create and open a connection to a SQL Server. Remember to use the Close() method to close the connection when you are done.

Listing D.1. Connecting to SQL Server
1: SqlConnection conn = SqlConnection("server=localhost;uid=sa;pwd=;database=MyGolfGear");
2: conn.Open();
3: //
4: // Do some work
5: //
6: conn.Close();

Note

In a Web application where you are using a connection string in multiple places, having to find all the connection strings is a maintenance nightmare when you need to change ...

Get Building e-Commerce Sites with the .NET Framework now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.