CONNECTING WITH SQL SERVER USING ADO.NET
STEPS WHILE WORKING WITH SQL SERVER :
-> Step 1: Import the library at the top.
1 |
using System.Data.SqlClient; |
->Step 2: Construct the “Connection” Class object.
1 |
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
1 |
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.
1 |
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:
1 |
con.Open(); |
-> Step 5: Construct the “Command” class object:
1 |
SqlCommand cmd= new SqlCommand(); |
-> Step 6: Assign the SQL Statement, which is to be executed:
1 |
cmd.CommandText="INSERT / UPDATE / DELETE / SELECT command"; |
-> Step 7: Assign the reference of connection object, to which the command is to be executed.
1 |
cmd.Connection=con; |
->Step 8: Execute the Command and receive the number of rows effected.
1 |
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:
1 |
con.Close(); |