// connect to database using SqlConnection connection = new SqlConnection("Data Source=server;Initial Catalog=database;Integrated Security=True"); // create command object using SqlCommand command = new SqlCommand("SELECT * FROM Employees WHERE LastName='Smith'", connection); // execute command and return result as object using SqlDataReader reader = command.ExecuteReader(); // loop through result set and display data while (reader.Read()) { Console.WriteLine("{0}\t{1}", reader["FirstName"], reader["LastName"]); }
// connect to database using SqlConnection connection = new SqlConnection("Data Source=server;Initial Catalog=database;Integrated Security=True"); // create command object using SqlCommand command = new SqlCommand("INSERT INTO Customers (FirstName, LastName) VALUES ('John', 'Doe')", connection); // execute command and return result as object int affectedRows = command.ExecuteNonQuery(); Console.WriteLine("{0} rows affected", affectedRows);Explanation: This example shows how to use ExecuteAsObject to execute an INSERT query to insert a new customer record into a SQL database. The result is returned as an int representing the number of rows affected by the query.