using System.Data.SqlClient; SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"); conn.Open(); string sql = "INSERT INTO Customers (Name, Address) VALUES ('John Doe', '123 Main St.')"; SqlCommand cmd = new SqlCommand(sql, conn); int rowsAffected = cmd.ExecuteNonQuery(); Console.WriteLine("Rows affected: " + rowsAffected); conn.Close();
using System.Data.SqlClient; SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"); conn.Open(); string sql = "UPDATE Customers SET Address='456 Oak St.' WHERE Name='John Doe'"; SqlCommand cmd = new SqlCommand(sql, conn); int rowsAffected = cmd.ExecuteNonQuery(); Console.WriteLine("Rows affected: " + rowsAffected); conn.Close();
using System.Data.SqlClient; SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True"); conn.Open(); string sql = "SELECT * FROM Customers"; SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["Name"] + " - " + reader["Address"]); } reader.Close(); conn.Close();This example connects to a database, selects all customer records, and loops through the result set to print the name and address of each customer. Package library: System.Data.SqlClient