Insert query in c#

Introduction:

A SQL statement called a "INSERT" query in C# is used to add new rows or records to a relational database table. Typically, MySQL, PostgreSQL, Microsoft SQL Server, and other databases are used with this query. It enables you to designate the values you wish to add to particular table columns.

Structure:

string insertQuery = "INSERT INTO TableName (Column1, Column2, Column3, ...) VALUES (@Value1, @Value2, @Value3, ...)";

Parameters:

  • put INTO TableName: The target table name that you wish to put data into is specified in this section. Change "TableName" to the table's real name.
  • (Column1, Column2, Column3,...): List the names of the table columns where you wish to put data inside the parenthesis. The columns should be specified in the same order as the values you supply.
  • VALUES: This keyword denotes that the values you wish to input will be specified.
  • (@Value1, @Value2, @Value3,...): To input data safely and securely, use parameterized values. via placeholders (such as "@Value1", "@Value2", etc.) in place of explicitly adding values allows you to specify the real values via query parameters.

Need of insert query:

  • Data entry: To add new information to a database, use INSERT queries. For every application, including order processing systems and registration forms, that has to gather and retain user-generated data, this is an essential function.
  • Database Population: You frequently need to add initial data to the database while developing and configuring an application. You may pre-load pertinent data into the database using INSERT queries.
  • User Registration: This is a feature that is frequently seen in applications. User data, including email address, password, and profile information, must be entered into the database when a user registers.
  • E-commerce and Inventory: INSERT queries are used to add goods and their details to databases in e-commerce systems and inventory management. This is essential for keeping current records of the things that are offered.
  • Logging and Auditing: You may use INSERT queries to log events, user actions, or system changes in order to maintain a record of activities and modifications inside an application. Security monitoring, troubleshooting, and auditing may all be done using this data.
  • Content Management: INSERT queries are used in content management systems (CMS) to add new articles, blog posts, photos, and other information to the database.
  • Comments and criticism: INSERT queries are used to store user-generated material in the database for apps that let users leave comments or criticism.
  • Forms and Surveys: A database is usually used to store the data from online forms and surveys. Later on, this data may be gathered and examined.
  • Order Processing: To record and handle orders in e-commerce, including customer information, product information, and delivery data, INSERT queries are utilised.
  • Websites that are dynamic: The material on these sites may be updated often. To add new posts, articles, or user-generated material, utilise INSERT queries.
  • Data Migration: INSERT queries are used to move records from one location to another when transferring data across databases or systems.
  • Application Back-End Operations: A lot of back-end services and systems depend on data insertion into databases for various back-end functions, including background tasks, caching, and analytics.

Example:

using System;


using System.Data;


using System.Data.SqlClient;


class Program


{


    static void Main()


    {


        string connectionString = "YourConnectionStringHere";


        // Create a new SqlConnection using the connection string


        using (SqlConnection connection = new SqlConnection(connectionString))


        {


            // Open the connection


            connection.Open();


            // Define the INSERT query


            string insertQuery = "INSERT INTO YourTableName (ColumnName1, ColumnName2) VALUES (@Value1, @Value2)";


            // Create a new SqlCommand with the query and the connection


            using (SqlCommand command = new SqlCommand(insertQuery, connection))


            {


                // Add parameters to the query to prevent SQL injection


                command.Parameters.AddWithValue("@Value1", "Value1");


                command.Parameters.AddWithValue("@Value2", "Value2");


                try


                {


                    // Execute the INSERT query


                    int rowsAffected = command.ExecuteNonQuery();


                    // Check the number of rows affected


                    if (rowsAffected > 0)


                    {


                        Console.WriteLine("Data inserted successfully.");


                    }


                    else


                    {


                        Console.WriteLine("No rows were inserted.");


                    }


                }


                catch (Exception ex)


                {


                    Console.WriteLine("Error: " + ex.Message);


                }


            }


        }


    }


}

Expected Output:

  • The first step involves creating a connection string, which you should change with the specifics of your database connection.
  • It uses the supplied connection string to create a connection to the database.
  • The "insertQuery" string is used to create an INSERT query, with the table name, column names, and parameter placeholders for the data to be inserted specified.
  • With the database connection and the INSERT query, a SqlCommand object is produced.
  • To define the values to be put, further parameters are supplied to the SqlCommand. The placeholders "@Value1" and "@Value2" in this example should be changed to the actual values you wish to put.
  • The code then makes an effort to use command.ExecuteNonQuery() to carry out the INSERT query. The number of rows impacted by the query is returned by this method.
  • Lastly, it returns a message indicating whether or not the data was successfully entered, depending on how many rows were impacted.