using System.Data.SqlClient; string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; string queryString = "SELECT * FROM Customers"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader[0] + "\t" + reader[1] + "\t" + reader[2]); } // Call Dispose when done with the reader. reader.Dispose(); }
using System.Data.SqlClient; string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"; string queryString = "UPDATE Customers SET ContactName = 'John Doe' WHERE CustomerID = 1"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(queryString, connection); connection.Open(); int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine("Rows affected: " + rowsAffected); // Call Dispose when done with the command object. command.Dispose(); }In this example, the SqlCommand is used to update data in a SQL Server database. The command is executed using the ExecuteNonQuery method that returns the number of rows affected by the query. Finally, Dispose method is called to release resources held by the command object. Package library: System.Data.SqlClient.