Database Reference
In-Depth Information
Connecting to SQL Server 2012 with SqlConnection
In this example, you'll connect to the SQL Server connect to the SQL Server 2012 AdventureWorks
database.
Try It: Using SqlConnection
You'll write a very simple program just to open and check a connection.
1. In Visual Studio 2011, create a new Windows Console Application project
named Chapter12. When Solution Explorer opens, save the solution.
2. Rename the Chapter12 project to ConnectionSQL. Rename the Program.cs file
to ConnectionSql.cs , and replace the generated code with the code in
Listing 12-1.
Listing 12-1. ConnectionSql.cs
using System;
using System.Data;
using System.Data.SqlClient;
namespace Chapter12
{
class ConnectionSql
{
static void Main(string[] args)
{
// Connection string (connection string key=value
//might be different for you based on your environment
string connString = @"server = .\sql2012; integrated security = true;";
// Create connection
SqlConnection conn = new SqlConnection(connString);
try
{
// Open connection
conn.Open();
Console.WriteLine("Connection opened.");
}
catch (SqlException ex)
{
// Display error
Console.WriteLine("Error: " + ex.Message + ex.StackTrace);
}
finally
{
// Close connection
 
Search WWH ::




Custom Search