1、概述

ado.net提供了丰富的数据库操作,这些操作可以分为三个步骤:

  • 第一,使用sqlconnection对象连接数据库;
  • 第二,建立sqlcommand对象,负责sql语句的执行和存储过程的调用;
  • 第三,对sql或存储过程执行后返回的“结果”进行操作。

对返回“结果”的操作可以分为两类:

  • 一是用sqldatareader直接一行一行的读取数据集;
  • 二是dataset联合sqldataadapter来操作数据库。

两者比较:

  • sqldatareader时刻与远程数据库服务器保持连接,将远程的数据通过“流”的形式单向传输给客户端,它是“只读”的。由于是直接访问数据库,所以效率较高,但使用起来不方便。
  • dataset一次性从数据源获取数据到本地,并在本地建立一个微型数据库(包含表、行、列、规则、表之间的关系等),期间可以断开与服务器的连接,使用sqldataadapter对象操作“本地微型数据库”,结束后通过sqldataadapter一次性更新到远程数据库服务器。这种方式使用起来更方,便简单。但性能较第一种稍微差一点。(在一般的情况下两者的性能可以忽略不计。)

一张十分出名的ado.net结构图:

2、连接字符串的写法

string connectstring = "data source=.;initial catalog=student;integrated security=true";

3、sqlconnection对象

命名空间:system.data.sqlclient.sqlconnection;

返回数据库连接对象,参数字符串。实例化“连接对象”,并打开连接

sqlconnection sqlcnt = new sqlconnection(connectstring);
sqlcnt.open();

使用完成后,需要关闭“连接对象”

sqlcnt.close();

4、sqlcommand对象

命名空间:system.data.sqlclient.sqlcommand;

sqlcommand对象用于执行数据库操作,操作方式有三种:

  • sql语句:command.commandtype = commandtype.text;
  • 存储过程:command.commandtype = commandtype.storedprocedure;
  • 整张表:command.commandtype = commandtype.tabledirect;

实例化一个sqlcommand对象

sqlcommand command = new sqlcommand();
command.connection = sqlcnt;            // 绑定sqlconnection对象

或直接从sqlconnection创建

sqlcommand command = sqlcnt.createcommand();     

常用方法:

  • command.executenonquery(): 返回受影响函数,如增、删、改操作;
  • command.executescalar():执行查询,返回首行首列的结果;
  • command.executereader():返回一个数据流(sqldatareader对象)。

常用操作

① 执行sql
sqlcommand cmd = conn.createcommand();              //创建sqlcommand对象
cmd.commandtype = commandtype.text;
cmd.commandtext = "select * from products = @id";   //sql语句
cmd.parameters.add("@id", sqldbtype.int);
cmd.parameters["@id"].value = 1;                    //给参数sql语句的参数赋值
② 调用存储过程
sqlcommand cmd = conn.createcommand();                      
cmd.commandtype = system.data.commandtype.storedprocedure;
cmd.commandtext = "存储过程名";
③ 整张表
sqlcommand cmd = conn.createcommand();    
cmd.commandtype = system.data.commandtype.tabledirect;
cmd.commandtext = "表名"

5、sqldatareader对象

命名空间:system.data.sqlclient.sqldatareader;

sqldatareader对象提供只读单向数据的功能,单向:只能依次读取下一条数据;只读:datareader中的数据是只读的,不能修改;相对地dataset中的数据可以任意读取和修改.

它有一个很重要的方法,是read(),返回值是个布尔值,作用是前进到下一条数据,一条条的返回数据,当布尔值为真时执行,为假时跳出。如

sqlcommand command = new sqlcommand();
command.connection = sqlcnt;
command.commandtype = commandtype.text;
command.commandtext = "select * from users";
sqldatareader reader = command.executereader();		//执行sql,返回一个“流”
while (reader.read())
{
    console.write(reader["username"]);	// 打印出每个用户的用户名
}

6、dataset对象

6.1 sqldataadapter;

命名空间:system.data.sqlclient.sqldataadapter;

sqldataadapter是sqlcommand和dataset之间的桥梁,实例化sqldataadapter对象:

sqlconnection sqlcnt = new sqlconnection(connectstring);
sqlcnt.open();

// 创建sqlcommand
sqlcommand mysqlcommand = new sqlcommand();
mysqlcommand.commandtype = commandtype.text;
mysqlcommand.commandtext = "select * from product";
mysqlcommand.connection = sqlcnt;

// 创建sqldataadapter
sqldataadapter mydataadapter = new sqldataadapter();
mydataadapter.selectcommand = mysqlcommand;	// 为sqldataadapter对象绑定所要执行的sqlcommand对象

上述sql可以简化为

sqlconnection sqlcnt = new sqlconnection(connectstring);
sqlcnt.open();
// 隐藏了sqlcommand对象的定义,同时隐藏了sqlcommand对象与sqldataadapter对象的绑定
sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
属性和方法
  • mydataadapter.selectcommand属性:sqlcommand变量,封装select语句;
  • mydataadapter.insertcommand属性:sqlcommand变量,封装insert语句;
  • mydataadapter.updatecommand属性:sqlcommand变量,封装update语句;
  • mydataadapter.deletecommand属性:sqlcommand变量,封装delete语句。
  • mydataadapter.fill():将执行结果填充到dataset中,会隐藏打开sqlconnection并执行sql等操作。

6.2 sqlcommandbuilder;

命名空间:system.data.sqlclient.sqlcommandbuilder。

对dataset的操作(更改、增加、删除)仅是在本地修改,若要提交到“数据库”中则需要sqlcommandbuilder对象。用于在客户端编辑完数据后,整体一次更新数据。具体用法如下:

sqlcommandbuilder mysqlcommandbuilder = new sqlcommandbuilder(mydataadapter);  // 为mydataadapter赋予sqlcommandbuilder功能
mydataadapter.update(mydataset, "表名");                   // 向数据库提交更改后的dataset,第二个参数为dataset中的存储表名,并非数据库中真实的表名(二者在多数情况下一致)。

6.3 dataset

命名空间:system.data.dataset。

数据集,本地微型数据库,可以存储多张表。

使用dataset第一步就是将sqldataadapter返回的数据集(表)填充到dataset对象中:

sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
dataset mydataset = new dataset();		// 创建dataset
mydataadapter.fill(mydataset, "product");	// 将返回的数据集作为“表”填入dataset中,表名可以与数据库真实的表名不同,并不影响后续的增、删、改等操作
① 访问dataset中的数据
sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
dataset mydataset = new dataset();
mydataadapter.fill(mydataset, "product");

datatable mytable = mydataset.tables["product"];
foreach (datarow myrow in mytable.rows) {
    foreach (datacolumn mycolumn in mytable.columns) {
        console.writeline(myrow[mycolumn]);	//遍历表中的每个单元格
    }
}
② 修改dataset中的数据
sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
dataset mydataset = new dataset();
mydataadapter.fill(mydataset, "product");

// 修改dataset
datatable mytable = mydataset.tables["product"];
foreach (datarow myrow in mytable.rows) {
    myrow["name"] = myrow["name"] + "商品";
}

// 将dataset的修改提交至“数据库”
sqlcommandbuilder mysqlcommandbuilder = new sqlcommandbuilder(mydataadapter);
mydataadapter.update(mydataset, "product");

注意:在修改、删除等操作中表product必须定义主键,select的字段中也必须包含主键,否则会提示“对于不返回任何键列信息的 selectcommand,不支持 updatecommand 的动态 sql 生成。”错误

③ 增加一行
sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
dataset mydataset = new dataset();
mydataadapter.fill(mydataset, "product");
datatable mytable = mydataset.tables["product"];

// 添加一行
datarow myrow = mytable.newrow();
myrow["name"] = "捷安特";
myrow["price"] = 13.2;
//myrow["id"] = 100; id若为“自动增长”,此处可以不设置,即便设置也无效
mytable.rows.add(myrow);

// 将dataset的修改提交至“数据库”
sqlcommandbuilder mysqlcommandbuilder = new sqlcommandbuilder(mydataadapter);
mydataadapter.update(mydataset, "product");
④ 删除一行
sqldataadapter mydataadapter = new sqldataadapter("select * from product", sqlcnt);
dataset mydataset = new dataset();
mydataadapter.fill(mydataset, "product");

// 删除第一行
datatable mytable = mydataset.tables["product"];
mytable.rows[0].delete();

sqlcommandbuilder mysqlcommandbuilder = new sqlcommandbuilder(mydataadapter);
mydataadapter.update(mydataset, "product");
属性
  • tables:获取包含在dataset中的表的集合。
  • relations:获取用于将表链接起来并允许从父表浏览到子表的关系的集合。
  • haseroors:表明是否已经初始化dataset对象的值。
方法
  • clear清除dataset对象中所有表的所有数据。
  • clone复制dataset对象的结构到另外一个dataset对象中,复制内容包括所有的结构、关系和约束,但不包含任何数据。
  • copy复制dataset对象的数据和结构到另外一个dataset对象中。两个dataset对象完全一样。
  • createdatareader为每个datatable对象返回带有一个结果集的datatablereader,顺序与tables集合中表的显示顺序相同。
  • dispose释放dataset对象占用的资源。
  • reset将dataset对象初始化。

7、释放资源

资源使用完毕后应及时关闭连接和释放,具体方法如下:

mydataset.dispose();        // 释放dataset对象
mydataadapter.dispose();    // 释放sqldataadapter对象
mydatareader.dispose();     // 释放sqldatareader对象
sqlcnt.close();             // 关闭数据库连接
sqlcnt.dispose();           // 释放数据库连接对象

转自:http://www.cnblogs.com/rainman/archive/2012/03/13/2393975.html