• ADO.NET


    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("	{0}	{1}	{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的概念等等。

  • 相关阅读:
    奇偶游戏(带权并查集)
    银河英雄传说(边带权并查集)
    程序自动分析(并查集+离散化)
    关于树状数组的小总结(树状数组)
    你能回答这些问题吗 (线段树)
    Phython 3 笔记3 —— 类,库与文件的读写
    Phython 3 笔记2 —— 基础语法
    Phython 3 笔记1 —— 基础容器
    CRJ巨佬gjd算法伪代码
    CRJ巨佬的gjd算法模板
  • 原文地址:https://www.cnblogs.com/mosakashaka/p/12607927.html
Copyright © 2020-2023  润新知