This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

13 Nov 2012

CONNECTING WITH SQL SERVER USING ADO.NET

STEPS WHILE WORKING WITH SQL SERVER  :

-> Step 1: Import the library at the top.
using System.Data.SqlClient;

->Step 2: Construct the "Connection" Class object.
 SqlConnection con = new SqlConnection();

-> Step 3: Assign the Connection String.

If u are using Windows authentication in Sql Server, then the  Connection string will be like this
con.ConnectionString = "Data Source=<Server Name>;Integrated Security=true;Initial Catalog=<Database Name>";

If you are using Sql Server authentication for Sql Server then the connection string is like this.
con.ConnectionString = "Data Source=<Server Name>;user id=<user name of sql server>;password=<password of sql server>;Initial Catalog=<Database Name>";


-> Step 4: Open the connection:
con.Open();

-> Step 5: Construct the  "Command" class object:
SqlCommand cmd= new SqlCommand();

-> Step 6: Assign the SQL Statement, which is to be executed:
cmd.CommandText="INSERT / UPDATE / DELETE / SELECT command";

-> Step 7: Assign the reference of connection object, to which the command is to be executed.
cmd.Connection=con;

->Step 8: Execute the Command and receive the number of rows effected.
int n=cmd.ExecuteNonQuery();

In the Above Statement we have to call the ExecuteNonQuery() method if the command Text Contains the "insert/update/delete" command.
If the Command is "Select" command, then we have to call the  ExecuteQuery( ) method instead of ExecuteNonQuery( )

-> Step 9: Close the Connection:
con.Close();

SIMPLE C# PROGRAM TO INSERT RECORDS INTO DATABASE USING ADO.NET ..

No comments:

Post a Comment

Thanks for your comments.
-Sameer