SQL Server Connection with Visual Studio 2010
1. Open Visual Studio 2010
• Launch Visual Studio 2010 and create a new project.
• Select 'Windows Forms Application' or 'ASP.NET Web Application', depending on your
requirement.
2. Open Server Explorer
• Go to 'View' → 'Server Explorer'.
• Right-click on 'Data Connections' → Select 'Add Connection'.
3. Configure Connection
• In the 'Add Connection' window:
- Select 'Microsoft SQL Server (SqlClient)' as the data source.
- Enter the 'Server Name' (e.g., .\SQLEXPRESS for local SQL Server Express).
- Choose 'Windows Authentication' or enter SQL 'username/password'.
- Select the database you want to connect to from the dropdown.
4. Test and Save Connection
• Click 'Test Connection'.
• If successful, click 'OK' to add the connection.
5. Use Connection in Code
Use the following C# code to establish a connection:
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Server=YOUR_SERVER_NAME;
Database=YOUR_DATABASE_NAME; Integrated Security=True;";
using (SqlConnection con = new SqlConnection(connectionString))
{
try
{
con.Open();
Console.WriteLine("Connection Successful!");
}
catch (Exception ex)
{
Console.WriteLine("Connection Failed: " + ex.Message);
}
}
}
}
Below is an example image of the SQL Server connection setup: