Simple C# program with ADO.NET
In this post i am posting a simple C# console program to start with ADO.NET. This may help the beginners in understanding the insertion of data into a database from a C# program.
Before going for the program create a table in sql server using the following command:
Now I am writing a C# program to insert data into the table EMP_DETAILS..
Before going for the program create a table in sql server using the following command:
1 |
CREATE TABLE EMP_DETAILS(EMP_ID INT,EMP_NAME VARCHAR(25)) |
Now I am writing a C# program to insert data into the table EMP_DETAILS..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
using System; using System.Data.SqlClient; //Namespace for connecting to sql server namespace First_DataBase_Program { class Program { static void Main(string[] args) { SqlConnection con = new SqlConnection(); SqlCommand cmd = new SqlCommand(); //if u r using windows authentication for sql server then ConnectionString is con.ConnectionString = "Data Source=LocalHost;Integrated Security=true;Initial Catalog=sameer"; /*if u r using sql authenticaton for sql server then ConectionString is con.ConnectionString = "Data Source=LocalHost;Initial Catalog=<database name>;user id=<user name>;password=<password>"; */ int Emp_Id = 0; string Emp_Name = "", option = "Y"; Console.WriteLine(">> Simple C# Console Program to Start with ADO.NET<<"); try { do { if (option != "Y"&& option != "y"&& option != "N"&& option != "n") { Console.Write("Press Y to continue and N to exit : "); option = Console.ReadLine(); } else { Console.Write("\n Enter employee id:"); Emp_Id = Convert.ToInt32(Console.ReadLine()); Console.Write("\n Enter Employee Name:"); Emp_Name = Console.ReadLine(); cmd.CommandText = "INSERT INTO Emp_Details VALUES(" + Emp_Id + ",'" + Emp_Name + "')"; cmd.Connection = con; con.Open(); cmd.ExecuteNonQuery(); con.Close(); Console.WriteLine("\n Command is:" + cmd.CommandText + "\n Record Inserted successfully"); } Console.Write("\n Press Y to continue and N to exit : "); option = Console.ReadLine(); } while (option != "N" || option == "n"); Console.ReadLine(); } catch (Exceptionex) { //Console.WriteLine("\n Error Occured...Try Again"); Console.Write(ex.Message); Console.ReadLine(); } } } } |
Execute the program to insert the records in the table EMP_DETAILS. The sample output is given below.
Now open the sql server and type the following command and execute.
1 |
SELECT * FROM EMP_DETAILS |
Then u can see the inserted records in the table EMP_DETAILS as shown below.
[…] previous posts we have seen CONNECTING WITH SQL SERVER USING ADO.NET , Simple C# program with ADO.NET […]
plz update me new issues in dot net……………….!
hay very nice ra wel don programmer………………….!