[Last Call] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 486
  • Last Modified:

Connect SQL Server from c# console application

hai friends,
how can i connect sql server from c# console application.pls give some sample codes.

thank you.

2 Solutions
You need to using System.Data.SqlClient or System.Data.Oledb. Here is an example that using System.Data.SqlClient namespace

using System;
using System.Data;
using System.Xml;
using System.Data.SqlClient;

namespace TestData
      /// <summary>
      /// Summary description for Class1.
      /// </summary>
      class Class1
            /// <summary>
            /// The main entry point for the application.
            /// </summary>
            static void Main(string[] args)
                  // create a connection
                  SqlConnection cn = new SqlConnection("Data Source=(local);User ID=sa;Password=khongbiet;Initial Catalog=northwind;");
                  // query string
                  string strSql = "Select FirstName, LastName From Employees";
                  SqlDataAdapter adapter = new SqlDataAdapter(strSql, cn);
                  // create datatable to store data from database
                  DataTable tblCity = new DataTable("Employee");
                  // fill data to data table
                  // print record
                  foreach (DataRow drowData in tblCity.Rows)
                        Console.WriteLine("FirstName: {0} - Lastname {1}", drowData["FirstName"].ToString(), drowData["FirstName"].ToString());

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now