How to Connect to Database using C#

 
Hi Friend this very simple program : How to Connect to Database using C#
using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
usingSystem.Windows.Forms;
usingSystem.Data.SqlClient; // SQL Server Connection
usingSystem.Data.OleDb; //Access Databse Connection
usingOracle.DataAccess.Client; //Oracle Databse Connection
//Oracle Connection add a reference of the assembly Oracle.DataAccess.dll.
namespaceHowToConnectSqlDatabase
{
    publicpartial class Form1 : Form
    {
       
        publicForm1()
        {
            InitializeComponent();
        }
  //Access Database Connection
        privatevoid AccessDatabase_Click(object sender, EventArgse)
        {
    OleDbConnectionOleCnn =new   
    OleDbConnection(“Provider=Microsoft.ACE.OLEDB.12.0;Data Source=”   
    +@”C:Northwind 2007.accdb”);
            OleDbCommandOldcmd;
           
            try
            {
                OleCnn.Open();
                Oldcmd = new OleDbCommand(“SELECT * From Employees”,OleCnn);
                Oldcmd.ExecuteNonQuery();
                MessageBox.Show(“Success”);
                OleCnn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
 //SQL Server Database Connection
  private void SQLServer_Click(objectsender, EventArgs e)
   {
     
    SqlConnection cnn = new SqlConnection(“Data Source=ServerName;Initial  
                                     Catalog=Databasename;Integrated Security=True”);
    SqlCommand cmd;
            try
            {
                cnn.Open();
                cmd = new SqlCommand(“SELECT * From Employees”,cnn);
                cmd.ExecuteNonQuery();
                MessageBox.Show(“Success”);
                cnn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

//Oracle Database Connection

private void Oracle_Click(objectsender, EventArgs e)
{
 OracleConnection Oracnn = new OracleConnection(“User ID=hr;Password=hr;Data    
 Source=ServerName;”);
 OracleCommand  OraCmd;
             try
            {
                Oracnn.Open();
                OraCmd = new OracleCommand(“SELECT * From Employees”, Oracnn);
                OraCmd.ExecuteNonQuery();
                MessageBox.Show(“Success”);
                Oracnn.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
      }
    }
// If you like this please share 

Leave a Reply

Your email address will not be published. Required fields are marked *