.NET 环境中的数据库交互OLE DB与SqlClient

ADO.NET 是 .NET 框架的基础数据访问技术,提供了与数据库直接交互的能力。SqlClientADO.NET 中用于访问 SQL Server 数据库的具体实现。

主要特点:
  • 直接数据访问:允许开发者直接编写 SQL 查询或存储过程来操作数据库,提供了更细粒度的控制。
  • 性能优化:相对于 ORM,ADO.NET 通常提供更高的性能,因为开发者可以直接控制查询和数据库交互。
  • DataSet 和 DataTable:支持使用 DataSet 和 DataTable 来处理数据,这对于需要在应用程序中处理离线数据的场景非常有用。
  • 存储过程:支持调用存储过程和执行参数化查询,提高了安全性和性能。

在 SQL Server 的数据访问中,主要的类包括:

  1. SqlConnection:用于建立与 SQL Server 数据库的连接。
  2. SqlCommand:用于执行 SQL 查询、存储过程或命令。
  3. SqlDataReader:用于读取从数据库返回的数据流。
  4. SqlDataAdapter:用于填充 DataSet 和更新数据源。
  5. SqlParameter:用于在 SQL 查询中传递参数。
  6. SqlTransaction:用于管理数据库事务。

这些类都是 ADO.NET 的一部分,专门用于 SQL Server 的数据交互

------------------- 

OLE DB(Object Linking and Embedding, Database)是一个微软开发的接口标准,用于访问各种数据源。它是一个在 Windows 操作系统上运行的 API,允许应用程序通过统一的方式访问关系型数据库、电子表格、文本文件以及其他数据源。

主要特点:

  1. 统一数据访问: OLE DB 提供了一个统一的接口,允许应用程序通过相同的 API 访问不同类型的数据源,无论是 SQL Server、Oracle 还是 Excel 文件。

  2. 组件架构: OLE DB 采用组件化设计,包括:

    • 数据源提供程序(Data Providers):实现了具体的数据访问功能。例如,SQL Server Native Client 是一个 OLE DB 数据源提供程序。
    • 数据服务组件(Data Services Components):提供额外的数据服务,如事务处理和缓存管理。
    • 数据消费者(Data Consumers):使用数据服务组件来获取和处理数据。
  3. 灵活性: OLE DB 支持各种数据存储格式,包括关系型和非关系型数据源。它不仅能访问 SQL 数据库,还能访问电子表格、文本文件等。

  4. 高性能: OLE DB 设计时考虑了性能,提供了高效的数据访问机制,特别是在处理大量数据时。

// Add necessary using directives
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "Data Source=localhost;Initial Catalog=tsl;User ID=sa;Password=xxxxxx";
        string query = "SELECT CustomerId, CustomerName, Email FROM Employees";

        try
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
                DataSet dataSet = new DataSet();

                adapter.Fill(dataSet, "Employees");

                DataTable employeesTable = dataSet.Tables["Employees"];

                // Modify data in the dataset
                foreach (DataRow row in employeesTable.Rows)
                {
                    // Corrected data type comparison
                    if (row["CustomerId"] != DBNull.Value && row["CustomerId"].ToString() == "12347")
                    {
                        row["CustomerName"] = "gggg";
                        row["Email"] = "gggggxxx@example.com";
                    }
                }

                // Manually set the update command
                string updateCommandText = "UPDATE Employees SET CustomerName = @CustomerName, Email = @Email WHERE CustomerId = @CustomerId";
                SqlCommand updateCommand = new SqlCommand(updateCommandText, connection);
                updateCommand.Parameters.Add("@CustomerName", SqlDbType.VarChar, 255, "CustomerName");
                updateCommand.Parameters.Add("@Email", SqlDbType.VarChar, 255, "Email");
                updateCommand.Parameters.Add("@CustomerId", SqlDbType.VarChar, 0, "CustomerId");
                adapter.UpdateCommand = updateCommand;

                // Update database with changes
                adapter.Update(dataSet, "Employees");

                // Display updated data
                foreach (DataRow row in employeesTable.Rows)
                {
                    Console.WriteLine("CustomerId: {0}", row["CustomerId"]);
                    Console.WriteLine("CustomerName: {0}", row["CustomerName"]);
                    Console.WriteLine("Email: {0}", row["Email"]);
                    Console.WriteLine();
                }

                Console.WriteLine("Data display completed.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: {0}", ex.Message);
        }

        Console.ReadLine();
    }
}





// SqlDataAdapter 类是ADO.NET中的一个重要组件,用于连接数据库并在 DataSet 和数据库之间传输数据。它充当了 DataSet 和关系型数据库之间的桥梁,负责填充数据集以及将数据集中的更改传输回数据库。
// 以下是 SqlDataAdapter 类的主要功能和用法:
// 数据填充(Data Population):SqlDataAdapter 可以执行 SQL 查询并将查询结果填充到 DataSet 中的一个或多个 DataTable 中。
// 数据更新(Data Update):SqlDataAdapter 可以将 DataSet 中的更改(如新增、修改、删除)传输回数据库。
// 数据加载(Data Loading):SqlDataAdapter 提供了 Fill 方法,可以从数据库中检索数据并填充到 DataSet 中。
// 数据同步(Data Synchronization):通过调用 Update 方法,SqlDataAdapter 可以将 DataSet 中的更改应用到数据库中,实现数据的同步。

using System;
using System.Data;
using System.Data.OleDb;

class Program
{
    static void Main()
    {
        // 定义连接字符串(示例中连接到一个Excel文件)
        string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\path\to\file.xlsx;Extended Properties='Excel 12.0 Xml;HDR=YES;'";

        // 定义SQL查询
        string query = "SELECT * FROM [Sheet1$]";

        // 创建一个DataSet实例
        DataSet dataSet = new DataSet();

        // 创建OleDbConnection实例并打开连接
        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            try
            {
                connection.Open();

                // 创建OleDbDataAdapter实例
                OleDbDataAdapter adapter = new OleDbDataAdapter(query, connection);

                // 使用OleDbDataAdapter填充DataSet
                adapter.Fill(dataSet, "Sheet1");

                // 获取DataTable
                DataTable table = dataSet.Tables["Sheet1"];

                // 处理数据
                foreach (DataRow row in table.Rows)
                {
                    Console.WriteLine($"Column1: {row[0]}, Column2: {row[1]}");
                }
            }
            catch (Exception ex)
            {
                // 处理异常
                Console.WriteLine("An error occurred: " + ex.Message);
            }
        }
    }
}
using System;
using System.Data.OleDb;

class Program
{
    static void Main()
    {
        string connectionString = "Provider=SQLOLEDB;Data Source=YourServer;Initial Catalog=YourDatabase;User ID=YourUsername;Password=YourPassword;";
        string query = "SELECT Id, Name FROM People";

        using (OleDbConnection connection = new OleDbConnection(connectionString))
        {
            OleDbCommand command = new OleDbCommand(query, connection);
            connection.Open();
            OleDbDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                int id = reader.GetInt32(0);
                string name = reader.GetString(1);
                Console.WriteLine($"Id: {id}, Name: {name}");
            }

            reader.Close();
        }
    }
}

  • 15
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值