Adding data
Glossary Item Box
Examples of using the Insert class to build queries for data insertion
You can download the package with the configuration web service implementing the cases described below using the following link.
The example code demonstrates available methods for passing parameters to the query. When developing a project, be aware that parameters originating from the user should never be passed to the Column.Const method, since this can lead to a successful SQL injection attack.
Example 1
public string GetSqlTextExample(string ContactName) { var result = ""; var id = Guid.NewGuid(); var ins = new Insert(UserConnection) .Into("Contact") .Set("Id", Column.Parameter(id)) .Set("Name", Column.Parameter(ContactName)); result = ins.GetSqlText(); return result; }
Example 2
public string InsertContact(string contactName) { contactName = contactName ?? "Unknown contact"; var ins = new Insert(UserConnection) .Into("Contact") .Set("Name", Column.Parameter(contactName)); var affectedRows = ins.Execute(); var result = $"Inserted new contact with name '{contactName}'. {affectedRows} rows affected"; return result; }
Example 3
public string InsertCity(string city, string country) { city = city ?? "unknown city"; country = country ?? "unknown country"; var ins = new Insert(UserConnection) .Into("City") .Set("Name", Column.Parameter(city)) .Set("CountryId", new Select(UserConnection) .Top(1) .Column("Id") .From("Country") .Where("Name") .IsEqual(Column.Parameter(country))); var affectedRows = ins.Execute(); var result = $"Inserted new city with name '{city}' located in '{country}'. {affectedRows} rows affected"; return result; }
See also