Home >Backend Development >C#.Net Tutorial >Database access techniques used in C#
What are the database access technologies in C#, specific code examples are required
In C# development, database access is a very common and important part. This article will introduce commonly used database access technologies in C# and provide some specific code examples to help readers understand and apply these technologies.
using System; using System.Data.SqlClient; namespace DatabaseAccess { class Program { static void Main(string[] args) { string connectionString = "YourConnectionString"; string query = "SELECT * FROM Customers"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["FirstName"] + " " + reader["LastName"]); } reader.Close(); } } } }
using System; using System.Linq; namespace DatabaseAccess { class Program { static void Main(string[] args) { using (var context = new YourDbContext()) { var customers = context.Customers.Where(c => c.Age > 18); foreach (var customer in customers) { Console.WriteLine(customer.FirstName + " " + customer.LastName); } } } } }
using System; using System.Data; using System.Data.SqlClient; using Dapper; namespace DatabaseAccess { class Program { static void Main(string[] args) { string connectionString = "YourConnectionString"; string query = "SELECT * FROM Customers WHERE Age > @Age"; using (IDbConnection connection = new SqlConnection(connectionString)) { var customers = connection.Query<Customer>(query, new { Age = 18 }); foreach (var customer in customers) { Console.WriteLine(customer.FirstName + " " + customer.LastName); } } } class Customer { public string FirstName { get; set; } public string LastName { get; set; } } } }
The above are three database access technologies commonly used in C#. They each have their own characteristics. Developers can choose the appropriate technology according to actual needs. By mastering these technologies, developers can interact with the database more conveniently and realize various business needs. We hope that the code examples provided in this article will be helpful to readers in their learning and development work in database access.
The above is the detailed content of Database access techniques used in C#. For more information, please follow other related articles on the PHP Chinese website!