Connecting to a SQL Server Express Database
You can connect to a SQL Server Express database just like you would connect to any SQL Server database by specifying the database server as the local SQL Server Express data source. For example, the following connection string connects to a database named Customers.
Data Source=.\SQLEXPRESS;Initial Catalog=Customers;Integrated Security=True;
You can also specify a database file to attach to by using the AttachDBFilename connection-string attribute in place of the InitialCatalog or Database connection-string attributes. Connecting to the database by using a file name simplifies deploying your database with your application (provided the target server is running SQL Server Express). For example, the following connection string connects to a database that is stored in the Customers.mdf file.
Data Source=.\SQLEXPRESS;AttachDbFileName=e:\data\Customers.mdf;Integrated Security=True;User Instance=True
ASP.NET provides a convenient option for storing data in the App_Data directory of a Web application. Contents of the App_Data directory are not served in response to Web requests, which improves the security of the data for your application. As an added convenience, you can supply the |DataDirectory| connection string variable in place of the file path to the App_Data directory for your application. ASP.NET features — such as the SqlDataSource control or the providers for membership, roles, user profiles, Web Parts personalization, and so on — will automatically substitute the file path to the App_Data directory for the |DataDirectory| connection-string variable when opening a connection to the database. This ensures that the path to your database remains current if your Web application is moved to a different directory. The following code example shows a connection string that includes the |DataDirectory| connection-string variable.
Data Source=.\SQLEXPRESS;AttachDbFileName=|DataDirectory|Customers.mdf;Integrated Security=True;User Instance=True
You can close the connection held by Visual Web Developer by right-clicking the database in Solution Explorer and selecting the Detach option, or by right-clicking the database in Server Explorer and selecting Close Connection. Visual Web Developer will automatically close any open database connections when you run or debug your Web application.
Additionally, if you need to release any open connections to a SQL Server Express database, you can unload your Web application by using Internet Information Services Manager (IIS Manager). You can also unload a Web application by adding an HTML file named App_offline.htm to the root directory of your Web application. To allow your Web application to start responding to Web requests again, simply remove the App_offline.htm file. You will need to release open connections to a SQL Server Express database when you want to copy or move the database to a new location.