connect to a microsoft sql in csharp

To connect to a Microsoft SQL Server database in C#, you can use ADO.NET which provides a set of classes for database connectivity.

Here's an example code snippet to connect to a Microsoft SQL Server database using ADO.NET:

main.cs
using System.Data.SqlClient;

string connectionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password";
SqlConnection conn = new SqlConnection(connectionString);

try
{
    conn.Open();
    // Connection opened successfully
}
catch (Exception ex)
{
    // Handle any errors
}
finally
{
    conn.Close();
}
348 chars
19 lines

In the above code, replace ServerName, DatabaseName, UserName, and Password with your own values. The SqlConnection class is used to create an instance of the connection to the database using the connection string. The Open method is called to open the connection, and the Close method is called in the finally block to close the connection.

With this connection established, you can execute commands against the database using other classes in ADO.NET such as SqlCommand and SqlDataReader.

gistlibby LogSnag