好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

C#使用SQL DataAdapter数据适配代码实例

数据适配

DataAdapter 对象是DataSet 和数据源之间的桥梁,可以建立并初始化数据表(即DataTable),对数据源执行SQL指令。与DataSet 对象结合,提供DataSet对象存取数据源执行SQL指令,与Dataset对象结合,提供Dataset对象存取数据,可视为Data对象操作核心。

在使用DataAdapter对象是,只需要设置SQL命令和数据库连接两个参数,就可以铜火锅Fill方法把查询结果放置在一个DataSet对象中;

实例 :

填充DataSet数据集:利用DataAdapter 的Fill方法实现 前提:有一个数据库MySql ,其下有个数据表mytable01,表中有数据

?

using System;

using System.Data.SqlClient;  //引用命名空间

using System.Data;

namespace DataAdapter

{

   class Program

   {

     static void Main( string [] args)

     {

       //连接数据库

       string constr = "Server=. ;user=sa;pwd=sa;database=MySql" ;

       SqlConnection mycon = new SqlConnection(constr);

       try

       {

         mycon.Open();

         string sql = "selecr * from mytable01" ;

         SqlDataAdapter myda = new SqlDataAdapter(sql, mycon);

         DataSet myds = new DataSet();

         myda.Fill(myds, "mytable01" );

         Console.WriteLine( "填充成功" );

         OutValues(myds);

         Console.Read();

       }

       catch (Exception ex)

       {

         Console.WriteLine(ex.Message.ToString());

       }

       finally

       {

         mycon.Close();

       }

      }

     public static void OutValues(DataSet ds)

     {

       foreach (DataTable dt in ds.Tables)

       {

         Console.WriteLine( "表名" +dt.TableName);

         foreach (DataRow row in dt.Rows)

         {

           foreach (DataColumn col in dt.Columns)

           {

             Console.Write(row[col] + "\t" );

           }

           Console.WriteLine();

         }

       }

     }   

   }

}

DataAdapter 对象可以用于执行数据库的命令操作,含有四个不同的执行操作命令,分别如下:

SelectCommand: 用来选取数据源中的记录 InsertCommand : 用来向数据源中新插入一条记录 UpdateCommand:用来更新数据源的数据 DeleteCommand : 用来删除数据源中的记录

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/Czhenya/article/details/77777590

dy("nrwz");

查看更多关于C#使用SQL DataAdapter数据适配代码实例的详细内容...

  阅读:49次