我想从应用程序中更改 SqlMapConfig.xml 文件中的数据库名称,有人帮助我吗?
问问题
805 次
1 回答
0
实例化 Ibatis mapper 实例时可以覆盖数据库;我这样做是为了在应用程序的调试和发布版本之间切换,从而访问不同的目标数据库。
例如,如果您的 xml 文件在一个名为的程序集中DatalayerAssembly
,您可能有一个方法可以根据数据库名称返回新的 Ibatis 实例,如下所示:
public IBatisNet.DataMapper.ISqlMapper CreateNewIbatis(
String serverName,
String databaseName)
{
// Load the config file (embedded resource in assembly).
System.Xml.XmlDocument xmlDoc = IBatisNet.Common.Utilities.Resources.GetEmbeddedResourceAsXmlDocument("SqlMapConfig.xml, DatalayerAssembly");
// Overwrite the connectionString in the XmlDocument, hence changing database.
// NB if your connection string needs extra parameters,
// such as `Integrated Security=SSPI;` for user authentication,
// then append that to InnerText too.
xmlDoc["sqlMapConfig"]["database"]["dataSource"]
.Attributes["connectionString"]
.InnerText = "Server=" + serverName + ";Database=" + databaseName;
// Instantiate Ibatis mapper using the XmlDocument via a Builder,
// instead of Ibatis using the config file.
IBatisNet.DataMapper.Configuration.DomSqlMapBuilder builder = new IBatisNet.DataMapper.Configuration.DomSqlMapBuilder();
IBatisNet.DataMapper.ISqlMapper ibatisInstance = builder.Configure(xmlDoc);
// Now use the ISqlMapper instance ("ibatisInstance") as normal.
return ibatisInstance;
}
我在 .Net 上的 Ibatis 1.6.2.0 中使用这种方法,但确切的 SqlMap 配置文件可能因版本而异。无论哪种方式,方法都是相同的;您可能只需要一个不同的 Xml 路径(即读取["sqlMapConfig"]["database"]
等的位可能需要为您的配置文件更改)
希望有帮助。
于 2014-08-08T23:37:20.747 回答