ADO - SQL Server - Insert Record

using System;
using System.Data.SqlClient;
class Program
{
    static void Main()
    {
        string connectionString = "Data Source=(local);Initial Catalog=YourDatabaseName;Integrated Security=True";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            try
            {
                connection.Open();
                // Connection opened successfully
                Console.WriteLine("Connected to the database.");
                // Insert a record
                string insertQuery = "INSERT INTO YourTableName (Id, Name) VALUES (@Id, @Name)";
                SqlCommand insertCommand = new SqlCommand(insertQuery, connection);
                
                // Set the parameter values
                insertCommand.Parameters.AddWithValue("@Id", 1);
                insertCommand.Parameters.AddWithValue("@Name", "John Doe");
                
                int rowsAffected = insertCommand.ExecuteNonQuery();
                Console.WriteLine($"Record inserted successfully. Rows affected: {rowsAffected}");
            }
            catch (Exception ex)
            {
                // Handle any errors
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
}

In the above code, make sure to replace "YourDatabaseName" with the actual name of the database you want to connect to, "YourTableName" with the name of the table you want to insert the record into, and provide appropriate values for the @Id and @Name parameters.

Here's an explanation of the code:

  • We start by defining the connection string, which includes the necessary details to connect to the SQL Server database. Update the "Data Source" to your server name or IP address, and "Initial Catalog" to your database name.
  • Inside the using block, we create a new SqlConnection object and pass the connection string as the constructor parameter. The using statement ensures that the connection is properly closed and disposed of when we're done with it.
  • We attempt to open the connection using the Open method. If the connection is successful, we print a message indicating that the connection has been established.
  • We define the SQL query to insert a record in the insertQuery variable. Replace "YourTableName" with the name of your table, and specify the column names and parameter placeholders (@Id and @Name) where the values will be provided later.
  • We create a new SqlCommand object with the insertQuery and the connection as parameters.
  • We set the parameter values using the Parameters.AddWithValue method of the SqlCommand object. Replace the parameter names and values (@Id and @Name) with the appropriate values for your record.
  • We execute the query using the ExecuteNonQuery method of the SqlCommand object. This method is used for executing queries that don't return any data. The ExecuteNonQuery method returns the number of rows affected by the query.
  • If the record insertion is successful, we print a message indicating that the record has been inserted, along with the number of rows affected.
  • If any errors occur during the process, they are caught in the catch block, and an error message is displayed.

Compile and run the code to establish a connection to your SQL Server database and insert the record.