Inserting Data To SQL Server using C#

Note : If you need whole compiled GUI application in c# please comment about what you need you will get that application in your email and please also share problems and errors which you faced while Developing these kind of database applications.  

For MySQL data insertion using JAVA (JDBC) visit JDBC Insert Data into My Sql using Prepared Statement

For C# first you will need to add Header files which are as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

  • If you are using C# you just need to add this header file only using System.Data.SqlClient;
  • I am using 2 text box and 1 date and time picker so according to this, the query will be as follows.

string query = “INSERT INTO [Order](Order_ID,Order_Date,Return_Date,Custumer_ID) VALUES (“ + textBox2.Text + “,” + textBox3.Text + “,” + dateTimePicker1.Value.ToShortDateString() + “,” + temp + ” )”;

  • You will need connection string which you can get by following procedure u can’t use this connection u have to make your own connection.

string connection = “Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database2.mdf;Integrated Security=True;User Instance=True”;

  • Click on Data and then on create new data sources
Create Data Sources

Create Data Sources


  • A Form will appear click on Data and then Click Next
data Source

data Source


  •  Now Select Your Data Connection and Copy Connection string  and click cancel.
Connection string

Connection string

  •  Your connection is ready.
  • Create new connection and pass this connection
  • Create new command ans pass your query and sql command instance that is conn
  • Now open this connection.
  • Now execute this command if your query is right then it will execute unless it will give exception.
  • Now close the connection You always need to close the connection unless you will receive exception if you will open connection again

SqlConnection conn = new SqlConnection(connection);
SqlCommand cmd = new SqlCommand(query, conn);

 Results Compiled Versi0n:



message box

message box


One Response

Leave a Reply