码迷,mamicode.com
首页 > Windows程序 > 详细

C#学习笔记 ----核心ADO.NET(第30章)

时间:2014-11-24 09:56:22      阅读:371      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   使用   sp   for   

ADO(Active Data Object)是一个COM组件库

 

DataSet 这个对象主要用于断开连接,它可以包含一组DataTable,以及这些表之间的关系

DataTable 数据的一个容器,DataTable由一个或多个DataColumn组成,每个DataColumen由一个或多个包含数据的DataRow组成

DataRow 许多数值,类似于数据库表的一行,或电子表格中的一行

DataColumn 该对象包含列的定义,如名称和数据类型

DataRelation DataSet类中两个DataTable类之间的链接,用于外键和主/从关系

Constraint 为DataColumn类(或一组数据列)定义规则,如唯一值

DataColumnMapping 将数据库中的列名映射到DataTable中的列名

DataTableMapping 将数据库中的表名映射到DataSet中的DataTable

 

SqlCommand、OleDbCommand和ODBCCommand用作SQL语句或存储过程调用的包装器

SqlCommandBuilder、OleDbCommandBuilder和ODBCCommandBuilder 用于从一条SELECT语句中生成SQL命令(如INSERT、UPDATE和DELETE语句)

SqlConnection、OleDbConnection和ODBCConnection用于连接数据库

SqlDataAdapter、OleDbDataAdapter和ODBCDataAdapter用于存储select、insert、update和delete命令的类,因此可以用于填充DataSet和更新数据库

SqlDataReader、OleDbDataReader和ODBCDataReader用作只向前的连接数据读取器

SqlParameter、OleDbParameter和ODBCParameter用于为存储过程定义一个参数

SqlTransaction、OleDbTransaction和ODBCTransaction用于数据库事务,包装在一个对象中

 

使用数据库连接

using System.Data.SqlClient

string source = "server=(loacal);"+"integrated security=SSPI;"+"database=Northwind";
SqlConnection conn = new SqlConnection(source);
conn.Open();
//Do something useful
conn.Close();

integrated security=SSPI:这个参数使用Windows Authentication连接到数据库,最好在源代码中使用这个参数,而不是用户名和密码

 

管理数据库连接字符串,使用配置文件中的<connectionString>

private DbConnection GetDatabaseConnection(string name)
{
    ConnectionStringSettings settings = ConfigurationManger.ConnectionStrings[name];
    DbProviderFactory factory = DbProviderFactories.GetFactory(settings.ProviderName);
    DbConnection conn = factory.CreateConnection();
    conn.ConnectionString = settings.ConnectionString;

    return conn;
}

 

高效的使用连接

1.利用 try...catch...finally语句块

try
{
    //Open the connection
    conn.Open();
    //Do something useful
}
cath(SqlException ex)
{
    //Log the exception
}
finally
{
    //Ensure that the connection is freed
    conn.Close();
}

2.使用using语句块

string source = "server=(loacal);"+"integrated security=SSPI;"+"database=Northwind";

using(SqlConnection conn = new SqlConnection(source))
{
    //Open the connection
    conn.Open();
    //Do something useful
}

组合使用

try
{
    using(SqlConnection conn = new SqlConnection(source))
    {
        //Open the connection
        conn.Open();
        //Do something useful
        //Close it myself
        conn.Close();
    }
}
catch(SqlException e)
{
    //Log the exception
}

 

事务

using(TransactionScope scope = new TransactionScope(TransactionScopeOption.Required))
{
    using(SqlConnection conn = new SqlConnection(source))
    {
        //Do something in SQL
        .
        //Then mark complete
        scope.Complete();
    }
}

在使用事务作用域时,可以选择在该事务中执行的命令的独立级别 ReadCommitted、ReadUncommitted、RepeatableRead、Serializable

 

命令

<provider>Command类有一个CommandType属性,一下列举CommandType枚举

string select = "SELECT ContactName FROM Customers"
SqlCommand cmd = new SqlCommand(select,conn);

SqlCommandcmd = new SqlCommand("CustOrderHist",conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@CustomerID","QUICK");

OleDbCommand cmd = new OleDbCommand("Categories",conn);
cmd.CommandType = CommandType.TableDirect;

<provider>Command类提供下述可执行命令:

ExecuteNonQuery() --执行命令,但不返回任何结果

ExecuteReader() --执行命令,返回一个类型化的IDataReader

ExecuteScalar() --执行命令,返回结果集中第一行第一列的值

除了上述命令,SqlCommand类也提供了下面的方法:

ExecuteXmlReader() --执行命令,返回一个XmlReader对象

 

ExecuteNonQuery() 一般用于UPDATE、INSERT或DELETE语句,其中唯一返回值是受影响的记录个数。但如果调出带输入参数的存储过程,该方法就有返回值

数据读取器

public class DataReaderExample
{
    public static void Main(string[] args)
    {
        string source = "Provider=SQLOLEDB;"+
                "server=(local);"+
                "integrated security=SSPI;"+
                "database=northwind";
        string select = "SELECT ContactName,CompanyName FROM Customers";
        OleDbConnection conn = new OleDbConnection(source);
        conn.Open();
        OleDbCommand cmd = new OleDbCommand(select,conn);
        OleDbDataReader aReader = cmb.ExecuteReader();
        while(aReader.Read())
            Console.WriteLine("‘{0}‘ from {1}",aReader.GetString(0),aReader.GetString(1));
        aReader.Close();
        conn.Close();
    }
}

 

DataSet类是数据的脱机容器

设置主键

DataColumn[] pk = new DataColumn[1];
pk[0] = dt.Columns["ProductID"];
dt.Constraints.Add(new UniqueConstraint("PK_Products",pk[0]));
dt.PrimaryKey = pk;

设置外键

DataColumn parent = ds.Tables["Categories"].Columns["CategoryID"];
DataColumn child = ds.Tables["Products"].Columns["CategoryID"];
ForeignKeyConstraint fk = new ForeignKeyConstraint("FK_Product_CategoryID",parent,child);
fk.UpdateRule = Rule.Cascade;
fk.DeleteRule = Rule.SetNull;
ds.Tables["Products"].Constraints.Add(fk);

 

填充DataSet类

用数据适配器填充DataSet

string select = "SELECT ContactName,CompanyName FROM Customers";
SqlConnectioin conn = new SqlConnection(source);
SqlDataAdapter da = new SqlDataAdapter(select,conn);
DataSet ds = new DataSet();
da.Fill(ds,"Customers");

从XML中填充DataSet类

DataSet ds = new DataSet();
ds.ReadXml(".\\MyData.xml");

 

C#学习笔记 ----核心ADO.NET(第30章)

标签:style   blog   io   ar   color   os   使用   sp   for   

原文地址:http://www.cnblogs.com/bmbh/p/4117982.html

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