ADO .Net – Dynamic Insertion of Record into SQL Server

Read Details and Insert Record into SQL Server:

  • In dynamic insertion, we take the input from the user through Console.ReadLine().
  • We create the SQL statement with variables such as @name….
  • We set the parameter values to Query before execution
using System;
using System.Data.SqlClient;
namespace ADO1
{
            internal class Program
            {
                        static void Main(string[] args)
                        {
                                    SqlConnection con = null;
                                    try
                                    {
                                                con = new SqlConnection(“data source=.; database=fullstack; integrated security=SSPI”);
                                                con.Open();
                                                Console.WriteLine(“Connected to Database”);
 
                                                Console.WriteLine(“Enter student details : “);
                                                int num = Convert.ToInt32(Console.ReadLine());
                                                String name = Console.ReadLine();
 
                                                String query = “insert into student values(@num, @name)”;
                                                SqlCommand cm = new SqlCommand(query, con);
 
                                                cm.Parameters.AddWithValue(“@num”, num);
                                                cm.Parameters.AddWithValue(“@name”, name);
 
                                                cm.ExecuteNonQuery();
                                                Console.WriteLine(“Record inserted successfully”);
                                    }
                                    catch (Exception e)
                                    {
                                                Console.WriteLine(“Exception : ” + e.ToString());
                                    }
                                    finally
                                    {
                                                if(con != null)
                                                {
                                                            con.Close();
                                                            Console.WriteLine(“Closed”);
                                                }
                                    }
                        }
            }
}
Scroll to Top