How to insert a row into a Microsoft SQL database using C#?
The following steps accomplishes this:
- Create a connection string.
- Create an insert query string.
- Create a SQLConnection object that uses the connection string.
- Create a SqlCommand object that used both the SQLConnection and the query string.
- Open the connection.
- Execute the query.
- 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();
}
}


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