码迷,mamicode.com
首页 > Web开发 > 详细

ADO.NET

时间:2020-03-31 21:18:26      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:cep   security   source   连接   不同   arp   resource   直接   csharp   

ADO.NET这个词之前听过很多次,但是没有去了解,但是这次不得不看一下。。

总的来说是用于操纵数据库的标准/接口/框架,确切不知道应能改如何形容。

 

似乎在此之前,操纵数据库需要一直维持一个连接,这对于很多应用来说应该是不可接受的,很多操作就是一个请求,进行一些CRUD。ADO.NET的描述是随用随开连接,现在我在使用时,觉得这种方式是司空见惯的,不了解在此之前是何种方式。。

 

ADO.NET有许多Provider,对应可能不同的数据库连接方式,或者接口使用方式。以一个sqlclient的provider为例子的代码:


using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString =
"Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=true";

    // Provide the query string with a parameter placeholder.
    string queryString =
        "SELECT ProductID, UnitPrice, ProductName from dbo.products "
            + "WHERE UnitPrice > @pricePoint "
            + "ORDER BY UnitPrice DESC;";

    // Specify the parameter value.
    int paramValue = 5;

    // Create and open the connection in a using block. This
    // ensures that all resources will be closed and disposed
    // when the code exits.
    using (SqlConnection connection =
        new SqlConnection(connectionString))
    {
        // Create the Command and Parameter objects.
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Parameters.AddWithValue("@pricePoint", paramValue);

        // Open the connection in a try/catch block. 
        // Create and execute the DataReader, writing the result
        // set to the console window.
        try
        {
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            while (reader.Read())
            {
                Console.WriteLine("\t{0}\t{1}\t{2}",
                    reader[0], reader[1], reader[2]);
            }
            reader.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        Console.ReadLine();
    }
}

可以看到,基本是

  1. 通过ConnectionString创建一个Connection
  2. 构造一个SqlCommand
  3. 打开Connection执行Command,获取结果

这里获取结果上,有DataReader和DataSet两种方式。实际上DataSet内部也是调用的DataReader。

想到上一次面试就被问到了DataReader和DataSet的差别,当时完全不了解。。。现在看来,DataReader是在直接读取结果不需要进一步操作时使用的,由于不需要将数据转存到DataSet中,效率高一些。

 

在使用这些Provider上,还是有很多需要了解的地方,比如提供出来的各种街口,各种Provider的概念等等。

ADO.NET

标签:cep   security   source   连接   不同   arp   resource   直接   csharp   

原文地址:https://www.cnblogs.com/mosakashaka/p/12607927.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!