
C#的数据库访问技术有哪些,需要具体代码示例
在C#开发中,数据库访问是非常常见且重要的一部分。本文将介绍C#中常用的数据库访问技术,并提供一些具体的代码示例,帮助读者了解和应用这些技术。
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; }
}
}
}以上是C#中常用的三种数据库访问技术,它们各有特点,开发者可以根据实际需求选择合适的技术。通过掌握这些技术,开发者可以更加便捷地与数据库进行交互,实现各种业务需求。希望本文提供的代码示例能够对读者在数据库访问方面的学习和开发工作有所帮助。
以上就是C#中使用的数据库访问技术的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号