zoukankan      html  css  js  c++  java
  • c# SQL Server数据库操作-数据适配器类:SqlDataAdapter

        SqlDataAdapter类主要在MSSQL与DataSet之间执行数据传输工具,本节将介绍如何使用SqlDataAdapter类来填充DataSet和MSSQL执行新增、修改。、删除等操作。

    功能说明

        SqlDataAdapter类构建在SqlCommand类之上,并提供了许多配合DataSet使用的功能。使用Fill方法可以把从MSSQL得到的查询结果填充到DataSet中。当DataSet中的数据发生了改变时,使用Update方法可以把更改后的数据更新到MSSQL。

    语法定义

        下面演示如何创建一个SqlDataAdapter类的实例:

        //无参数
        SqlDataAdapter adapter = new SqlDataAdapter();
        //指定CommandText对象构建一个SqlDataAdapter实例
        SqlDataAdapter adapter = new SqlDataAdapter("select * from Products");
        //指定CommandText和SqlConnection对象构建一个SqlDataAdapter实例
        SqlConnection connection = new SqlConnection();
        SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connection);

    方法详解

        SqlDataAdapter类提供了很多重要的方法

        Fill方法和Update方法最为常用,也拥有多个重载。

        Fill方法的使用:

    static void Main(string[] args)
    {
         string connectionString = "Data Source=ip;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa; Password=sa";
         SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connectionString);
         DataSet ds = new DataSet();
         adapter.Fill(ds,"Products"); //填充DataSet并指定表名为"Products"
         foreach (DataRow dr in ds.Tables["Products"].Rows)
         {
             Console.WriteLine(dr["ProductName"].ToString());
         }
    }


    注意:使用SqlDataAdapter类时,无须手工调用SqlConnection对象的Open方法。SqlDataAdapter类会自动打开连接,执行完后会自动恢复SqlConnection对象的连接状态。

    UpDtae方法的使用:

    static void Main(string[] args)
    {
        string connectionString = "Data Source=ip;Initial Catalog=Northwind;Persist Security Info=True;User ID=sa; Password=sa";
        SqlDataAdapter adapter = new SqlDataAdapter("select * from Products",connectionString);
        DataSet ds = new DataSet();
        adapter.Fill(ds,"Products"); //填充DataSet并指定表名为"Products"
        ds.Tables["Products"].Rows[0].Delete();   //删除一行数据
       SqlCommand deleteCommand = new SqlCommand();
        //...此处省略了deleteCommand的属性设置
       adapter.DeleteCommand = deleteCommand;
        if (adapter.Update(ds) > 0)   //调用Update方法更新数据
       {
            Console.WriteLine("更新成功");
         }
    }
  • 相关阅读:
    java中获取类加载路径和项目根路径的5种方式分析
    浅谈HTTP中Get与Post的区别
    Http请求工具类 httputil
    Java中遍历数组的三种方式复习
    关于if else 和 三目运算符的效率问题-java
    EXCEL设置三级下拉框
    Java Web前端到后台常用框架介绍
    Shiro学习(总结)
    Shiro学习(24)在线回话管理
    使用jsr303实现数据校验
  • 原文地址:https://www.cnblogs.com/lihaibo-Leao/p/3164585.html
Copyright © 2011-2022 走看看