How to insert a row into a Microsoft SQL database using C#?

The following steps accomplishes this:

  1. Create a connection string.
  2. Create an insert query string.
  3. Create a SQLConnection object that uses the connection string.
  4. Create a SqlCommand object that used both the SQLConnection and the query string.
  5. Open the connection.
  6. Execute the query.
  7. Close the connection.
Steps are in the code with comments.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace InsertToDatabase
{
	public class InsertToDatabase
	{
		// Step 1 - Create a connection string.
		string connectionString = @"Data Source = ServerName; user id=UserName; password=P@sswd!; Initial Catalog = DatabaseName;";
		// Step 2 - Create an insert query string
		string query = "INSERT INTO Users (Firstname, Lastname, Email) VALUES ('Jared','Barneck','Jared.Barneck@somedomain.tld')";
		// Step 3 - Create a SQLConnection object that uses the connection string.
		SqlConnection connection = new SqlConnection(connectionString);
		// Step 4 - Create a SqlCommand object that used both the SQLConnection and the query string.
		SqlCommand command = new SqlCommand(query, connection);
		// Step 5 - Open the connection.
		connection.Open();
		// Step 6 - Execute the query.
		command.ExecuteNonQuery();
		// Step 7 - Close the connection.
		connection.Close();
	}
}

One Comment

  1. Markin Tyler says:

    Thank you so much! As a newb I appreciate this wholly.

Leave a Reply

How to post code in comments?