How to pass data through variables and insert the values into database table using SqlCommand Statement with C#
Let's create our table
first:
CREATE TABLE [dbo].[Member](
[Id] [int] NULL,
[Name] [varchar](60) NULL,
[Dob] [date] NULL,
[Email]
[varchar](80) NULL,
[Phone]
[Nvarchar](20) NULL
)
The below C# script
can be used to insert the variable values to “dbo.Member” table just created .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.IO;
namespace DataWorldWithGbengaOridupa.com_CSharp_Tutorial
{
class Program
{
static void Main(string[] args)
{
//The datetime and Log folder
will be used for error log file in case of error. It is important.
string datetime =
DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Create
Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "Data Source = (local);
Initial Catalog = DataworldWithGbengaOridupa; "
+ "Integrated Security=true;";
//Now Declare
variables and set values
Int32 id =
1;
string
Name = "Olu Paul";
string dob
= "1986/06/02";
string email
= "testingPaul@gmail.com";
//Now Prepare
Insert Query by using variables
string
InsertQuery = "";
InsertQuery = " Insert into dbo.Member(id,name,dob,email)";
InsertQuery += "Values(" + id + ",'" + Name + "','" +dob + "', '" + Email + "')";
//Execute
Insert Query to Insert Data into SQL Server Table
SqlCommand
cmd = SQLConnection.CreateCommand();
cmd.CommandText = InsertQuery;
SQLConnection.Open();
cmd.ExecuteNonQuery();
SQLConnection.Close();
}
catch
(Exception exception)
{
//This
will Create Log File for Errors
using
(StreamWriter sw = File.CreateText(LogFolder
+
"\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());
}
}
}
}
}
first off, a hearty thanks to you. Your blog is awesome and completely knowledgeable and I completely satisfied with the reading. Keep your work spread till long after. For more coding classes for kids related information visit Techno Smart Kids.Certainly, you are Right!!
ReplyDeleteI generally check this kind of article and I found your article which is related to my interest.Hni database india Genuinely it is good and instructive information. Thankful to you for sharing an article like this.
ReplyDeleteI will share it with my other friends as the information is really very useful. Read more info about private coding tutor. Keep sharing your excellent work.
ReplyDelete