@jaylen.trantow
В C# существует несколько способов работы с базами данных:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
using System; using System.Data.SqlClient; public class Program { public static void Main() { string connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Database\SampleDB.mdf;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); SqlCommand command = new SqlCommand("SELECT * FROM Customers", connection); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine(reader["Name"]); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using System; using System.Linq; public class Program { public static void Main() { using (var context = new SampleDBEntities()) { var customers = from c in context.Customers select c; foreach (var customer in customers) { Console.WriteLine(customer.Name); } } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
using System; using System.Data.SqlClient; using Dapper; public class Program { public static void Main() { string connectionString = "Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Database\SampleDB.mdf;Integrated Security=True"; using (SqlConnection connection = new SqlConnection(connectionString)) { var customers = connection.Query("SELECT * FROM Customers"); foreach (var customer in customers) { Console.WriteLine(customer.Name); } } } } public class Customer { public int Id { get; set; } public string Name { get; set; } } |
Каждый из этих подходов имеет свои преимущества и недостатки, и выбор подхода зависит от конкретных требований и предпочтений разработчика.
@jaylen.trantow
В C# существует несколько способов работы с базами данных:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
using System.Data.SqlClient; string connectionString = "Your Connection String"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM MyTable"; using (SqlCommand command = new SqlCommand(sql, connection)) { using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { // read data } } } } |
1 2 3 4 5 6 7 8 9 10 |
using MyApp.Models; using (var context = new MyDbContext()) { var customers = context.Customers.ToList(); foreach (var customer in customers) { // do something with customer } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 |
using Dapper; string connectionString = "Your Connection String"; using (SqlConnection connection = new SqlConnection(connectionString)) { connection.Open(); string sql = "SELECT * FROM MyTable"; var results = connection.Query(sql); foreach (var result in results) { // do something with result } } |
Выбор подхода зависит от требований вашего проекта и предпочтений разработчика.