Data Base Handling [Using Code]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
public partial class Registration : System.Web.UI.Page
{
SqlConnection cn;
SqlCommand cm;
SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{ //step 1- connection to database
string path =@"Data Source=49.50.88.43;Initial Catalog=grkistdb;Persist Security Info=True;User ID=grkistuser;Password=q2oR5w_356";
cn = new SqlConnection(path);
cn.Open();
//step 2- Command (write a query)
string q = "insert into Chitransh_stu values('" + TextBox1.Text + "' , '" + TextBox2.Text + "' , '" + TextBox3.Text + "' , '" + TextBox4.Text + "' , '" + TextBox5.Text + "' , '" + TextBox6.Text + "')";
cm = new SqlCommand(q, cn);
//step 3- execute the query
cm.ExecuteNonQuery();
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
TextBox5.Text = "";
TextBox6.Text = "";
}
}
How to connect to data base-
step 1-
Include SqlClient library to your project .
With the help of using keyword ,at the top of the page.
i.e- using System.Data.SqlClient;
step 2-
Create objects for connection, command and data reading.
Objects are always created before the Page_load event.
>SqlConnection cn;
>SqlCommand cm;
>SqlDatareader dr;
Note:- In OOPs , Firstly the information (database path, Query) stored in a variable and pass to an object.
The operation can be performed in 3 steps:-
Step1 - Connection to database
string s =@"path";
[here the path will be stored in a variable s , @ symbol is used to identify the path no spaces between = and @]
cn = new SqlConnection(s);
[here cn is the object of SqlConnection , the variable in which the path is stored will get passed into the object in the parameter]
cn.open();
[To open the database]
Step2 - Command
string q= "Query";
cm = new SqlCommand(q,cn);
SqlCommand holds two parameters first for the variable and second for the connection.
Step3 - Execute the query
cm.ExecuteNonQuery();
[here we use insertion operation so insertion operation comes under ExecuteNonQuery ]
Comments
Post a Comment