Select Insert update and delete into SQL SERVERdatabase using C#.net

Insert data into database:

 string constring = @"Data Source=Servername;Initial Catalog=databasename;Integrated Security=True";

        string a=TextBox1.Text;

        string b = TextBox2.Text;


        SqlConnection conn = new SqlConnection(constring);

        string query= "INSERT INTO t1 (c1,c2)" + " values('" + a + "','" + b+ "')";

        SqlCommand sqlCmd = new SqlCommand( query, conn);
        conn.Open();
        sqlCmd.ExecuteNonQuery() ;
        conn.Close();

Select data from database and show into Datagridview:

SqlConnection con = new SqlConnection(constring);
            //Open database connection to connect to SQL Server
            con.Open();
            //Data table is used to bind the resultant data
            DataTable dtusers = new DataTable();
            // Create a new data adapter based on the specified query.
            SqlDataAdapter da = new SqlDataAdapter("SELECT  * FROM HTable ORDER BY Deadline ASC ", con);
            //SQl command builder is used to get data from database based on query
            SqlCommandBuilder cmd = new SqlCommandBuilder(da);
            //Fill data table
            da.Fill(dtusers);
            //assigning data table to Datagridview
            dataGridView1.DataSource = dtusers;
            //Resize the Datagridview column to fit the gridview columns with data in datagridview
            dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            con.Close();

Delete data into database:

  SqlConnection conn = new SqlConnection(constring);

            string query = "Delete  from table where userid=umar ";

            SqlCommand sqlCmd = new SqlCommand(query, conn);
            conn.Open();
            sqlCmd.ExecuteNonQuery();// insertion into db
            conn.Close();
            MessageBox.Show("data is deleted");

Update data from database :

 SqlConnection conn = new SqlConnection(constring);

            string query = "UPDATE Customers SET ContactName='Muhammad Umar' 
WHERE userid='Umarz'";

            SqlCommand sqlCmd = new SqlCommand(query, conn);
            conn.Open();
            sqlCmd.ExecuteNonQuery();// insertion into db
            conn.Close();
            MessageBox.Show("data is updated");

By Muhammad Umar hayat



Comments