Ado Connection, Class and Object

Download as pdf or txt
Download as pdf or txt
You are on page 1of 4

C# Object and Class

Since C# is an object-oriented language, program is designed using objects and


classes in C#.

C# Object
In C#, Object is a real world entity, for example, chair, car, pen, mobile, laptop etc.

In other words, object is an entity that has state and behavior. Here, state means data
and behavior means functionality.

Object is a runtime entity, it is created at runtime.

Object is an instance of a class. All the members of the class can be accessed through
object.

Let's see an example to create object using new keyword.

Student s1 = new Student();//creating an object of Student

//SAMPLE PROGRAM

1. using System;
2. public class Student
3. {
4. public int id;
5. public String name;
6. public void insert(int i, String n)
7. {
8. id = i;
9. name = n;
10. }
11. public void display()
12. {
13. Console.WriteLine(id + " " + name);
14. }
15. }
16. class TestStudent{
17. public static void Main(string[] args)
18. {
19. Student s1 = new Student();
20. Student s2 = new Student();
21. s1.insert(101, "Ajeet");
22. s2.insert(102, "Tom");
23. s1.display();
24. s2.display();
25.
26. }
27. }

oUTPUT:

Output:

101 Ajeet
102 Tom
ADO.NET SqlConnection Class

It is used to establish an open connection to the SQL Server database.

It is a sealed class so that cannot be inherited.

SqlConnection class uses SqlDataAdapter and SqlCommand classes together to increase


performance when connecting to a Microsoft SQL Server database

SqlConnection Constructors

Constructors Description

SqlConnection() It is used to initializes a new instance of the SqlConnection class.

SqlConnection(String)0 It is used to initialize a new instance of the SqlConnection class and takes
connection string as an argument.

SqlConnection(String, It is used to initialize a new instance of the SqlConnection class that


SqlCredential) takes two parameters. First is connection string and second is sql
credentials.

SqlConnection Example

1. using (SqlConnection connection = new SqlConnection(connectionString))


2. {
3. connection.Open();
4. }
sAMPLE PROGRAM

1. using System;
2. using System.Data.SqlClient;
3. namespace AdoNetConsoleApplication
4. {
5. class Program
6. {
7. static void Main(string[] args)
8. {
9. new Program().Connecting();
10. }
11. public void Connecting()
12. {
13. using (
14. // Creating Connection
15. SqlConnection con = new SqlConnection("data source=.; database=stu
dent; integrated security=SSPI")
16. )
17. {
18. con.Open();
19. Console.WriteLine("Connection Established Successfully");
20. }
21. }
22. }
23. }

You might also like