To do an interaction with a database system you have to create a connection to the server. This connection basically contains the location of the database, database name, a username and password of a database and some other parameters.
To create a connection object you create an instance of SqlConnection class. You need to pass a connection string to the constructor of this object. After creating a connection you have to call the Open() method to open the database connection.
After having the connection object ready you can start using it to manipulate the database with the help of the SqlCommand object. Let’s see an example below for creating and opening a connection.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Data; using System.Data.SqlClient; namespace Kodecsharp { class SqlConnectionExample { static void Main(string[] args) { // // Define the connection string to the database. // string connectionString = @"Data Source=.\\SQLEXPRESS; Initial Catalog=Northwind; Integrated Security=SSPI;"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); if (connection.State == ConnectionState.Open) { Console.WriteLine("Connection is ready to be used."); } // Do something with the connection object. } } } } |