Connection 类的方法(Connection Class Method Reference)

BeginTransaction:

IDbTransaction = Connection.BeginTransaction();
IDbTransaction 
= Connection.BeginTransaction(IsolationLevel iso);
IDbTransaction 
= Connection.BeginTransaction(String transactionName);
IDbTransaction 
= Connection.BeginTransaction(IsolationLevel iso,
String transactionName);


返回一个强类型的IDbTransaction object,代表一个客户初始化的Transaction。
这个Transaction从Command.Transaction属性开始,到IDbTransaction object的commit或者rollback结束。

IsolationLevel iso参数:
这个参数设置Transaction的独立性。Isolationlevel的级别越高,产生数据错误的几率越低。
String transactionName参数:
给Transaction命名,当建立功能接近的多个Transaction时,命名就很有用处了。
使用Transaction的例子:
建立了一个Transaction,包括了2个Command, 在最后执行完提交,遇到错误rollback。

string connectionString = "Data Source=localhost;" +
"Initial Catalog=Northwind;Integrated Security=SSPI";
string SQL1 = "INSERT INTO Categories (CategoryName, Description) " +
"VALUES ('Beverages', 'Soft drinks')";
string SQL2 = "UPDATE Categories SET Description ='Coffee and tea' " +
"WHERE CategoryName='Beverages'";
SqlConnection con 
= new SqlConnection(connectionString);
SqlCommand cmdA 
= new SqlCommand(SQL1, con);
SqlCommand cmdB 
= new SqlCommand(SQL2, con);
int rowsAffected;
SqlTransaction tran 
= null;
try
{
con.Open();
// Start the transaction.
tran = con.BeginTransaction();
// Enlist the commands.
cmdA.Transaction = tran;
cmdB.Transaction 
= tran;
// Execute the commands.
rowsAffected = cmdA.ExecuteNonQuery();
rowsAffected 
+= cmdB.ExecuteNonQuery();
// Commit the transaction.
tran.Commit();
}

catch
{
tran.Rollback();
}

finally
{
con.Close();
}



注意:一个客户端发起的Transaction,需要从客户端到数据源进行操作的来回,要先开始,然后操作,然后提交或者会滚。整个过程有延时,从性能上说,比数据库的存储过程要低。当执行BeginTrasaction()方法时,后续的命令都封装在Transaction操作里面,执行完后,根据结果,在执行commit或者rollback,涉及到很多步操作。
如果可能,用数据库的带Transaction的存储过程代替客户端发起的Transaction,实现的功能相同,效率却更高。


ChangeDatabase():
Connection.ChangeDatabase(string databasename);
这个方法改变当前连接的数据库名称。更新后,后续的命令都将在更新的数据库执行。这个命令对应SqlServer的USE命令。使用此命令时,数据库联接必须是打开的。
String databasename参数:指定了要使用的信息数据库名称,当指定了不存在的数据库名称时,会发生SqlException。
例子:
建立一个连接,执行2个命令,第一个命令操作数据库Northwind,第2个操作Pubs。

string connectionString = "Data Source=localhost;" +
"Initial Catalog=Northwind;Integrated Security=SSPI";
string SQL1 = "UPDATE Categories SET Description='Coffee and tea' " +
"WHERE CategoryName='Beverages'";
string SQL2 = "UPDATE Titles SET Title='The Busy Executive' " +
"WHERE Title_Id='BU1032'";
SqlConnection con 
= new SqlConnection(connectionString);
SqlCommand cmdA 
= new SqlCommand(SQL1, con);
SqlCommand cmdB 
= new SqlCommand(SQL2, con);
int rowsAffected;
try
{
con.Open();
// Execute the first command using the Northwind database.
rowsAffected = cmdA.ExecuteNonQuery();
// Execute the second command using the pubs database.
con.ChangeDatabase("pubs");
rowsAffected 
+= cmdB.ExecuteNonQuery();
}

finally
{
con.Close();
}


注意: 可以使用连接字符串的Initial Catalog参数来设定初始化的数据库。Oracle不支持这个方法。


Close():
Connection.Close();
这个方法关闭数据库联接。如果数据库已经断开连接,那么不会报错。Close()除了断开数据库联接,如果存在Transaction,还会做Rollback;如果需要,还可以释放到Connection Pooling的资源。
注意:Close()比Dispose()更好,因为Dispose() destory 数据库联接,并且不返回给connection pooling。为了保证数据库连接可以顺利关闭,最后放在try{}catch{} finally{}的finally里面,即使出现错误,也可以正常关闭连接。

CreateCommand():
IDbCommand command=Connection.CreateCommand();
返回一个强类型的IDbCommand object,用于执行Sql Command。

EnlistDistributeTransaction()
EnlistDistributeTransaction(Itransaction transaction);
如果auto-enlistment 被禁用,那么这个方法将把Connection加入到指定的、活动的、distribute transaction中。当这个Transation 执行commit或者rollback后,使用这个连接的,对数据库的任何改动也会随之commit或者rollback。
Itransaction transaction参数:已经存在的,将被使用的数据库连接。
例子:

// create the connection with auto-enlistment disabled
SqlConnection conn = new SqlConnection(
"Data Source=localhost;Integrated Security=SSPI;" +
"Initial Catalog=Northwind;Enlist=false;");
SqlCommand cmd 
= new SqlCommand();
// define the command to update the data source
conn.Open();
// get the current COM+ DTC transaction,
// and enlist the connection if the transaction exists
ITransaction tran = (ITransaction)ContextUtil.Transaction;
if(tran != null)
conn.EnlistDistributedTransaction(tran);
try
{
// execute the command against the data source
cmd.ExecuteNonQuery();
// vote to commit after successful command
ContextUtil.SetComplete();
}

catch (SqlException ex)
{
// vote to roll back if an error occurs
ContextUtil.SetAbort();
}

finally
{
conn.Close();
}


注意:在连接字符串中使用Enlist=false(SqlServer)或者Ole Db Services=-7,可以禁止Auto-Enlist.使用EnlistDistributedTransaction()前必须打开数据库连接;如过执行这个方法时,已经执行了BeginTrasaction(),那么会发生错误。如果存在一个本地的Transaction,那么这个transaction会自动rollback,没有提示,Connection 会自动Enlist Distributed Transaction。

GetOleDbSchemaTable()
OleDb Only.
DataTable dt=Connection.GetOleDbSchemaTable(Guid schema,Object Restrictions);
返回一个数据表,代表获取数据库的结构的信息,可以包括:列数据类型,约束,表名,视图名称,数据库使用者等等。
参数:
Guid schema:Guid(globally unique identifier),代表返回的Rowset的shema。每一种schema table都是由OleDb 唯一标示。既可以设置必须的值手工建立一个Guid,也可以使用OleDbSchemaGuid类的公用方法来获取一个Guid。
Object Restrictioins:包含限定值的集合。
Eg:

string connectionString = "Data Source=localhost;" +
"Provider=SQLOLEDB;Initial Catalog=Northwind;" +
"Integrated Security=SSPI";
OleDbConnection con 
= new OleDbConnection(connectionString);
DataTable schema;
try
{
con.Open();
schema 
= con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables,
new object[] {nullnullnull"TABLE"});
}

finally
{
con.Close();
}

// Display the schema table.
foreach (DataRow row in schema.Rows)
{
Console.WriteLine(row[
"TABLE_TYPE"+ "" +
row[
"TABLE_NAME"]);
}


Open()
Connection.Open();
这个方法打开一个通过ConnectionString定义的数据库的连接。如果存在连接池,那么将使用池中第一个可用的连接,如果没有可用的连接并且没有达到最大值,那么建立一个新的连接。


ReleaseObjectPool
OleDb Only
Connection.ReleaseObjectPool();
这个方法释放连接池的资源。当没有连接需求时,可以使用这个方法。
这个方法很少用,因为连接池使用的资源并不多,没有必要让程序指定连接使用多长时间后手工关闭。

参考:
ADO.NET in a Nutshell
By Bill Hamilton, Matthew MacDonald
April 2003

posted on 2005-06-06 15:18  Pierce  阅读(1758)  评论(0编辑  收藏  举报

导航