Insert data

Insert data

Let us add the below function to the program class in order to insert data

static void WriteData()
{
    try
    {
        using (SqlConnection connection = new SqlConnection(ConString))
        {
            var cmd = new SqlCommand("insert into Student values (105, 'Ramesh', 'Ramesh@dotnettutorial.net', '1122334455')", connection);
            connection.Open();
            
            var rowsAffected = cmd.ExecuteNonQuery();
            Console.WriteLine("Inserted Rows = " + rowsAffected);
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("OOPs, something went wrong.\n" + e);
    }
}

Call the function

We can then call the above function from the main method, the modified code structure must look as shown below:

Can you try update and delete operations similarly?

Last updated