string connectionString = "Data Source=MySqlServer;Initial Catalog=MyDatabase;User ID=sa;Password=password"; SqlConnection connection = new SqlConnection(connectionString); // Open the connection. connection.Open(); // Create a command object to execute the INSERT statement. SqlCommand command = new SqlCommand("INSERT INTO Customers (FirstName, LastName, Email) VALUES ('John', 'Doe', '[email protected]')", connection); // Execute the INSERT statement. int rowsAffected = command.ExecuteNonQuery(); // Close the connection. connection.Close();
using System.Data.SqlClient; ... string connectionString = "Data Source=MySqlServer;Initial Catalog=MyDatabase;User ID=sa;Password=password"; using (SqlConnection connection = new SqlConnection(connectionString)) { // Open the connection. connection.Open(); // Create a command object to execute the INSERT statement. string query = "INSERT INTO Customers (FirstName, LastName, Email) VALUES (@FirstName, @LastName, @Email)"; SqlCommand command = new SqlCommand(query, connection); // Set the parameter values. command.Parameters.AddWithValue("@FirstName", "Jane"); command.Parameters.AddWithValue("@LastName", "Doe"); command.Parameters.AddWithValue("@Email", "[email protected]"); // Execute the INSERT statement. int rowsAffected = command.ExecuteNonQuery(); // Close the connection. connection.Close(); }This example uses a parameterized query to add a new record to the Customers table. Parameterized queries are a best practice to prevent SQL injection attacks. It also uses the `using` statement for automatic disposal of resources and to make the code cleaner. The package library for System.Data.SqlClient is the .NET Framework Class Library.