對于使用ADO.NET通用接口創(chuàng)建對象
對于ADO.NET通用接口的相關使用還是比較常見,就使用ADO.NET DbProviderFactories并擴充兼容mysql我深入的研究了一下,我們現(xiàn)在一起來看看吧。ADO.NET2.0 為各種ADO.NET類引入了一個提供程序工廠的模型以及通用基類。
ADO.NET通用接口的限制:接口不易擴展,ADO.NET1.1無法創(chuàng)建某些類的實例,ADO.NET1.1無法判斷可用的.NET數(shù)據(jù)提供程序。提供工廠模型如何解決上述限制,通過抽象積累來擴展ADO,NET模型。#t#
使用ADO.NET DbProviderFactories類來創(chuàng)建對象。提供程序工廠模型的限制,許多查詢結構都是數(shù)據(jù)庫特有的。為參數(shù)化查詢設置CommandText時,可能需要提供程序特有的代碼,指定參數(shù)數(shù)據(jù)類型可能需要提供程序特有的代碼。為了使開發(fā)的代碼通用。
不局限于特定的數(shù)據(jù)庫,本次開發(fā)中決定使用DbProviderFactory+標準SQL,以開發(fā)一個適用于mysql和 sqlserver的封裝,但DbProviderFactories 并沒有提供對mysql的DbProviderFactory的支持,所以需要擴充ADO.NET通用接口兼容mysql,而且在ADO.net 2.0中mysql和sqlserver的ParameterMarkerFormat都有bug,ADO.NET通用接口所以擴展類要解決這個bug。
- public static class DbProviderFactoriesEx {
- public static DbProviderFactory GetFactory(string providerName) {
- if (providerName == null) throw new ArgumentNullException("providerName");
- DbProviderFactory dbFactory; switch (providerName)
- { case "MySql.Data.MySqlClient": return new MySqlClientFactory();
- default: return DbProviderFactories.GetFactory(providerName); } }
- public static string GetParameterMarkerFormat(DbConnection connect)
- { if (connect == null) throw new ArgumentNullException("connect");
- Type type = connect.GetType(); if (type == typeof(MySql.Data.MySqlClient.MySqlConnection))
- return "?{0}";//mysql bug if (type == typeof(System.Data.SqlClient.SqlConnection))
- return "@{0}";//ms bug connect.Open(); string result = connect.GetSchema("DataSourceInformation").Rows[0]["ParameterMarkerFormat"].ToString();
- connect.Close(); return result; } }