Next


Connecting with the Database

connection-with-the-database
 In the above diagram, “cn” is an object, that is able to maintain the connection with the database.
 The cn is an object for “Connection” class (SqlConnection or OleDbConnection).

Implementation of Connection with “System.Data.SqlClient” (For Sql Server):

 Import the API:
using System.Data.SqlClient;
 Prepare the Connection string:
string cnstr = “data source=<name of the server>;user id=<user name>;password=<password>;initial catalog=<database name>”;
 Construct the “Connection” class object:
SqlConnection cn = new SqlConnection(cnstr);
 Open the connection:
cn.Open();
 Close the connection: cn.Close();

Implementation of Connection with “System.Data.OleDb” (For Other db’s):

 Import the API:
using System.Data.OleDb;
 Prepare the Connection string:
Oracle
string cnstr = “provider=oraoledb.oracle.1;data source=<name of the server>user id=<user name>;password=”;
MS Access
string cnstr = “provider=microsoft.jet.oledb.4.0;data source=<path of the db file>”;
 Construct the “Connection” class object:
OleDbConnection cn = new OleDbConnection(cnstr);
 Open the connection:
cn.Open();
 Close the connection:
cn.Close();

Demo on Database Connection



using System.Data.SqlClient;
using System.Data.OleDb;
private void btnSqlServer_Click(object sender, EventArgs e)
{
string cnstr = "data source=.;user id=sa;password=123;initial catalog=master";
SqlConnection cn = new SqlConnection(cnstr);
cn.Open();
MessageBox.Show("Successfully Connected with Sql Server");
cn.Close();
}
private void btnOracle_Click(object sender, EventArgs e)
{
string cnstr = "provider=oraoledb.oracle.1;data source=.;user id=scott;password=tiger";
OleDbConnection cn = new OleDbConnection(cnstr);
cn.Open();
MessageBox.Show("Successfully Connected with Oracle");
cn.Close();
}
private void btnMSAccess_Click(object sender, EventArgs e)
{
string cnstr = "provider=microsoft.jet.oledb.4.0;data source=c:\\database1.mdb";
OleDbConnection cn = new OleDbConnection(cnstr);
cn.Open();
MessageBox.Show("Successfully Connected with MS Access");
cn.Close();
}