First of all, we will create a database and table followed by insertion of data in table. We will be using the following queries.

  1. create database EmployeeDatabase
  2. use EmployeeDatabase
  3. Create Table EmployeeDetails
  4. (
  5. Name varchar(50),
  6. Email varchar(50),
  7. Salary varchar(30),
  8. Department varchar (50)
  9. )
  10. select * from EmployeeDetails
  11. INSERT INTO EmployeeDetails(Name, Email, Salary, Department)
  12. VALUES ('ram', '[email protected]', '35000', 'IT');

Secondly, we will create a new project and choose console application in C# and give a name to the project as SqlConnectionDemo, and write the following code in our program.cs

  1. using System;
  2. using System.Data.SqlClient;
  3. namespace SqlConnectionDemo
  4. {
  5. /// <summary>
  6. ///ADO.NET is an object oriented libraries that allows us to interact with database and we weill learn how to connect with sqldatabase using ADO.NET
  7. /// </summary>
  8. class Program
  9. {
  10. public void SelectData()
  11. {
  12. // Create object(instance) of sql connection which will provide a connection to the data source(database) to read and write database
  13. SqlConnection cn = new SqlConnection(@"data source=DESKTOP-6DF0CN3\SQLEXPRESS; Database=EmployeeDatabase; integrated security = true");
  14. // Sql command allow data adpeters to read, add, update and delete the records in a data source.
  15. // Data adapters support 4 properties that give us access to these objects - select, insert, update adn delete for creating queries to database.
  16. // Sqlcommand perform a query on the EmployeeDetails
  17. SqlCommand cmd = new SqlCommand("select * from EmployeeDetails", cn);
  18. // Open the connection by calling open() method of sqlconnection object cn
  19. cn.Open();
  20. //holds a read only, forward only set of data from a database.
  21. //using a sql Data Reader can increase speed because only one row of data is in memory at a time.
  22. // result set is returned as SqlDataReader
  23. SqlDataReader rdr = cmd.ExecuteReader();
  24. // While Loop Read the first column from each row of result set which is employee name
  25. while (rdr.Read())
  26. {
  27. // Print employee details
  28. Console.WriteLine(rdr[0] + " " + rdr[1] + " " + rdr[2]+ " " + rdr[3]);
  29. }
  30. // Close the reader by calling CLose() method
  31. rdr.Close();
  32. // Close the connection by calling close() method
  33. cn.Close();
  34. }
  35. static void Main(string[] args)
  36. {
  37. // Create the object of Program class P
  38. Program p = new Program();
  39. // invoke the SelectData () Method
  40. p.SelectData();
  41. Console.ReadLine();
  42. }
  43. }
  44. }

Output

ram [email protected] 35000 IT