Wednesday 11 April 2012

DataBase Connectivity in c#


using System;
using System.Data.SqlClient;

class Program
{
static void Main()
{
SqlConnection con=new SqlConnection();
SqlCommand cmd=new SqlCommand();
int n;
string command;

con.ConnectionString="server=.;database=Student;integrated security=true;";
cmd.Connection=con;

// command="CREATE TABLE student(Sno INT PRIMARY KEY IDENTITY(1,1),Sname VARCHAR(30),Cname VARCHAR(30),Duration INT)";
// cmd.CommandText=command;

// con.Open();
// Console.WriteLine("Connected to Sql Server");
// cmd.ExecuteReader();
// Console.WriteLine("Table Created Successfully");
// con.Close();

command="INSERT INTO student(Sname,Cname,Duration) VALUES ('SMRITI DABGAR','.NET',90)";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Inserted Successfully",n);
con.Close();

command="DELETE FROM student WHERE sno=1";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Deleted Successfully",n);
con.Close();

command="UPDATE student SET sname='ANKUR BHATNAGAR' WHERE sno=2";
cmd.CommandText=command;

con.Open();
n=cmd.ExecuteNonQuery();
Console.WriteLine("{0} Records Updated Successfully",n);
con.Close();

command="SELECT count(*) FROM student WHERE Cname='.NET'";
cmd.CommandText=command;

con.Open();
object ob=cmd.ExecuteScalar();
Console.WriteLine("Total No Of Records in .NET is: {0}",(int)ob);
con.Close();
}
}

No comments:

Post a Comment