How to connect to a database and run a SQL command by using ADO.NET

  1. Follow these steps to create a new console application in Microsoft Visual C# .NET:
    1. Start Microsoft Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click Console Application under Templates.
  2. Make sure that your project contains a reference to the System.Data namespace, and add a reference if it does not.
  3. Use the using statement on the System and System.Data namespaces so that you do not have to qualify declarations in those namespaces later in your code.
  4. Before you can create a connection to a database, you must have a connection string. Connection strings contain all of the information that you need to establish a database connection, including the server name, the database name, the user ID, and the password. For example, the following connection string points to a local computer that is running SQL Server:
        <add name="MainConnectionString"
            connectionString="Data Source=(local);Initial Catalog=[DB];User ID=[UID];Password=[PWD];Persist Security Info=True;"
            providerName="System.Data.SqlClient" />

Download Sample C# Console Application Project

How to connect to a database and run a command by using ADO.NET 2005