First of all, we will create a database and table followed by insertion of data in table. We will be using the following queries.
- create database EmployeeDatabase
- use EmployeeDatabase
-
- Create Table EmployeeDetails
- (
- Name varchar(50),
- Email varchar(50),
- Salary varchar(30),
- Department varchar (50)
- )
- select * from EmployeeDetails
-
- INSERT INTO EmployeeDetails(Name, Email, Salary, Department)
- 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
- using System;
- using System.Data.SqlClient;
-
- namespace SqlConnectionDemo
- {
-
-
-
- class Program
- {
- public void SelectData()
- {
-
- SqlConnection cn = new SqlConnection(@"data source=DESKTOP-6DF0CN3\SQLEXPRESS; Database=EmployeeDatabase; integrated security = true");
-
-
-
- SqlCommand cmd = new SqlCommand("select * from EmployeeDetails", cn);
-
- cn.Open();
-
-
-
- SqlDataReader rdr = cmd.ExecuteReader();
-
- while (rdr.Read())
- {
-
- Console.WriteLine(rdr[0] + " " + rdr[1] + " " + rdr[2]+ " " + rdr[3]);
- }
-
- rdr.Close();
-
- cn.Close();
- }
- static void Main(string[] args)
- {
-
- Program p = new Program();
-
- p.SelectData();
- Console.ReadLine();
- }
- }
- }
Output
ram [email protected] 35000 IT