xxxxxxxxxx
using System.Data.SqlClient;
// create a connection to the database
string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;Integrated Security=True";
SqlConnection connection = new SqlConnection(connectionString);
// define the query with parameters
string query = "INSERT INTO myTable (column1, column2) VALUES (@value1, @value2)";
// create a new SqlCommand object with the query and connection
SqlCommand command = new SqlCommand(query, connection);
// set the parameter values
command.Parameters.AddWithValue("@value1", "some value");
command.Parameters.AddWithValue("@value2", 123);
// open the connection to the database
connection.Open();
// execute the command
int rowsAffected = command.ExecuteNonQuery();
// close the connection
connection.Close();
myServerAddress and myDataBase should be replaced with the appropriate values for your database. The column1 and column2 values should be replaced with the names of the columns you are inserting data into. The @value1 and @value2 placeholders are the parameter names used in the query and should match the names used when setting the parameter values.
xxxxxxxxxx
using(var connection = new SqlConnection("connectionString"))
{
connection.Open();
var sql = "INSERT INTO Main(FirstName, SecondName) VALUES(@FirstName, @SecondName)";
using(var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@FirstName", txFirstName.Text);
cmd.Parameters.AddWithValue("@SecondName", txSecondName.Text);
cmd.ExecuteNonQuery();
}
}