connect sql server database in csharp

Here is an example of how to connect to a SQL Server database using C# and ADO.NET:

main.cs
using System.Data.SqlClient;
using System.Configuration;

string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    // Use the connection here
}
292 chars
10 lines

You will need to replace "MyConnectionString" with the name of your connection string as defined in your app.config or web.config file, and make sure to include the necessary using statements at the top of your file.

In the above example, we create a SqlConnection object using the connection string and open the connection using the Open() method. You can then use the connection to execute SQL commands against the database.

gistlibby LogSnag