Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Delete data from sql server(C#)

Delete data from sql server(C#)

Scheduled Pinned Locked Moved C#
csharpdatabasesql-serversysadminquestion
7 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Member 10484848
    wrote on last edited by
    #1

    hi friends How i can delete data from data base(sql server) in C#?????

    A S R 3 Replies Last reply
    0
    • M Member 10484848

      hi friends How i can delete data from data base(sql server) in C#?????

      A Offline
      A Offline
      Ade Ruyani Z
      wrote on last edited by
      #2

      this is simple script to delete using webform asp.net C# here is my code: 1. adding connection in Web.config Web.config ==========

      <connectionStrings>
      <add name="myConnection" providerName="System.Data.SqlClient" connectionString="server=.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True"/>
      </connectionStrings>

      2. in default.aspx default.aspx ============ added namespace: using System.Data.SqlClient; using System.Configuration;

      protected void Page_Load(object sender, EventArgs e)
      {
      if (!IsPostBack)
      {
      string connProvider = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
      using (SqlConnection cnn = new SqlConnection(connProvider))
      {
      cnn.Open();
      string userid = "1";
      string query = "Delete Users Where UserID = '" + userid + "'";
      using (SqlCommand cmd = new SqlCommand(query, cnn))
      {
      cmd.ExecuteNonQuery();
      }
      }
      }
      }

      hope this help. (Update)= this code not recommended for develop, you can try it for learn and you can improve your code. regard, Ade Ruyani

      OriginalGriffO 1 Reply Last reply
      0
      • A Ade Ruyani Z

        this is simple script to delete using webform asp.net C# here is my code: 1. adding connection in Web.config Web.config ==========

        <connectionStrings>
        <add name="myConnection" providerName="System.Data.SqlClient" connectionString="server=.\SQLEXPRESS;Initial Catalog=MyDB;Integrated Security=True"/>
        </connectionStrings>

        2. in default.aspx default.aspx ============ added namespace: using System.Data.SqlClient; using System.Configuration;

        protected void Page_Load(object sender, EventArgs e)
        {
        if (!IsPostBack)
        {
        string connProvider = ConfigurationManager.ConnectionStrings["myConnection"].ToString();
        using (SqlConnection cnn = new SqlConnection(connProvider))
        {
        cnn.Open();
        string userid = "1";
        string query = "Delete Users Where UserID = '" + userid + "'";
        using (SqlCommand cmd = new SqlCommand(query, cnn))
        {
        cmd.ExecuteNonQuery();
        }
        }
        }
        }

        hope this help. (Update)= this code not recommended for develop, you can try it for learn and you can improve your code. regard, Ade Ruyani

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #3

        Reason for my downvote: Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. Even in a simple example like this, it takes hardly any extra work to do it properly!

        Never underestimate the power of stupid things in large numbers --- Serious Sam

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        A 1 Reply Last reply
        0
        • OriginalGriffO OriginalGriff

          Reason for my downvote: Do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead. Even in a simple example like this, it takes hardly any extra work to do it properly!

          Never underestimate the power of stupid things in large numbers --- Serious Sam

          A Offline
          A Offline
          Ade Ruyani Z
          wrote on last edited by
          #4

          Thank you sam, this is just a simple code, whether they can improve they're code using store procedure or else.

          L 1 Reply Last reply
          0
          • M Member 10484848

            hi friends How i can delete data from data base(sql server) in C#?????

            S Offline
            S Offline
            Simon_Whale
            wrote on last edited by
            #5

            int RowsAffected = 0;
            using(SqlConnection cn = new SqlConnection(ConnectionStringHere))
            {
            cn.Open();

            using(SqlCommand cmd = new SqlCommand())
            {
            cmd.Connection = cn;
            cmd.CommandType = CommandType.Text;

             //This shows how to delete with a simple where clause
             cmd.CommandText = "Delete from tablename where id = @id"; 
             cmd.Parameters.AddWithValue("@id",id);
             RowsAffected = cmd.ExecuteNonQuery();
            

            }
            }

            Every day, thousands of innocent plants are killed by vegetarians. Help end the violence EAT BACON

            1 Reply Last reply
            0
            • A Ade Ruyani Z

              Thank you sam, this is just a simple code, whether they can improve they're code using store procedure or else.

              L Offline
              L Offline
              Lost User
              wrote on last edited by
              #6

              Ade.Ruyani.Z wrote:

              this is just a simple code

              It is still a bad example, because it leads to careless coding.

              Veni, vidi, abiit domum

              1 Reply Last reply
              0
              • M Member 10484848

                hi friends How i can delete data from data base(sql server) in C#?????

                R Offline
                R Offline
                Rahul Rajat Singh
                wrote on last edited by
                #7

                You can use ado.net: A Beginner's Tutorial for Understanding ADO.NET[^] Or any ORM like entity framework for the same: An Introduction to Entity Framework for Absolute Beginners[^]

                Twenty years from now you will be more disappointed by the things that you didn't do than by the ones you did do. So throw off the bowlines. Sail away from the safe harbor. Catch the trade winds in your sails. Explore, Dream. Discover.

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups