Rabu, 28 Agustus 2013

How to open and close connections with ADO.NET

ADO.NET enables applications to connect to data sources and manipulate the data.  In ADO.NET object model, the data is retrieved through a data provider. An application can access data either through a dataset or a data reader.

You have to create a connection and then provide connection string, to move data between data source and an application. SqlConnection class is used to open a connection and also have some more methods:
  • ConnectionString: It is a property provides information like database name and data source.
  • Open (): used to open a connection. It Needs connection string to open a connection.
  • Close (): used to close an existing connection.
For example, the following code will create an object of SqlConnection class and then create a connection a connection string to the database in c# language.
SqlConnection connection = new SqlConnection();
connection.ConnectionString = “Data Source=(LocalDB)\v11.0;Initial Catalog=StockDb; Integrated Security=True”;

Here in the above code i have used the connection string of database name "StockDb". After you have defined the connection string, you need to open the connection by using open() method as written below
connection.Open();

Do all your work related to database and at the last you have to close the connection using close() method as written below
connection.Close();

Tidak ada komentar:

Posting Komentar