connect to in csharp

To connect to a SQL Server database in C#, you need to use ADO.NET libraries, which provides classes for working with data from a data source, such as a SQL Server database. The following code shows an example of connecting to a SQL Server database using ADO.NET:

main.cs
using System.Data.SqlClient;

// Set the connection string
string connectionString = "Data Source=serverName;Initial Catalog=databaseName;User ID=userName;Password=password";

// Create a new SqlConnection object
using (SqlConnection connection = new SqlConnection(connectionString))
{
    // Open the connection
    connection.Open();
    
    // Execute SQL commands here using the connection object
    // ...
    
    // Close the connection
    connection.Close();
}
472 chars
18 lines

In the above code, you first set the connection string that includes the server name, database name, username, and password. Then you create a new SqlConnection object and pass in the connection string. You can use the Open() method on this object to open the connection to the database. Once the connection is open, you can execute any SQL commands using this connection such as SqlCommand and SqlDataReader. Finally, you should call the Close() method to close the connection when you're finished.

gistlibby LogSnag