INSERT Statements
To create new records, use INSERT statements.
INSERT Syntax
The INSERT statement specifies the columns to be inserted and the new column values. You can specify the column values in a comma-separated list in the VALUES clause, as shown in the following example:
INSERT INTO <table_name>
( <column_reference> [ , ... ] )
VALUES
( { <expression> | NULL } [ , ... ] )
<expression> ::=
| @ <parameter>
| ?
| <literal>
You can use the ExecuteNonQuery method to execute data manipulation commands and retrieve the rows affected, as shown in the following example:
C#
String connectionString = "URI=C:\MyExcelWorkbooks\SampleWorkbook.xlsx;"; using (ExcelConnection connection = new ExcelConnection(connectionString)) { int rowsAffected; ExcelCommand cmd = new ExcelCommand("INSERT INTO Sheet (LastName) VALUES ('White')", connection); rowsAffected = cmd.ExecuteNonQuery(); }
VB.NET
Dim connectionString As [String] = "URI=C:\MyExcelWorkbooks\SampleWorkbook.xlsx;" Using connection As New ExcelConnection(connectionString) Dim rowsAffected As Integer Dim cmd As New ExcelCommand("INSERT INTO Sheet (LastName) VALUES ('White')", connection) rowsAffected = cmd.ExecuteNonQuery() End Using
Retrieving Generated Ids
In order to retrieve the RowId of the last inserted record, use the SCOPE_IDENTITY function, as shown in the following example:C#
cmd = connection.CreateCommand(); cmd.CommandText = "SELECT SCOPE_IDENTITY()"; Object returnedValues = cmd.ExecuteScalar(); String RowId = (String)returnedValues;
VB.NET
cmd = connection.CreateCommand() cmd.CommandText = "SELECT SCOPE_IDENTITY()" Dim returnedValues As [Object] = cmd.ExecuteScalar() Dim RowId As [String] = returnedValues