c#直接调用ssis包实现Sql Server的数据导入功能
调用ssis包实现Sql Server的数据导入功能网上已经有很多人讨论过,自己参考后也动手实现了一下,上一次笔者的项目中还用了一下这个功能。思前想后,决定还是贴一下增强记忆,高手请54. 1、直接调用ssis包,需要引用Microsoft.SqlServer.DTSRuntimeWrap.dll,客户端需要安装MS SQL Server2005的客户端组件。 2、调用代码
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
/// <summary> /// /通过SSIS包 将数据导入数据库 /// </summary> /// <param name="dtsxFileName">dtsx文件名</param> /// <param name="csvFileName">csv文件名</param> /// <returns></returns> protected bool FillData2DB(string dtsxFileName, string csvFileName) { string dtsxFile = System.AppDomain.CurrentDomain.BaseDirectory + "DTSX\\" + dtsxFileName;
Microsoft.SqlServer.Dts.Runtime.Wrapper.Application app = new Microsoft.SqlServer.Dts.Runtime.Wrapper.Application();
//Call the dtsx file IDTSPackage90 package = app.LoadPackage(dtsxFile, true, null); //另外还有一种方法叫LoadFromSQLServer package.Connections["File"].ConnectionString = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, csvFileName); package.Connections["本地连接"].ConnectionString = ConfigurationSettings.AppSettings["ConnStr"];
DTSExecResult result = package.Execute(); //获取包的执行信息 //string message = string.Empty; //if (result.Equals(DTSExecResult.DTSER_FAILURE)) //{ // for (int i = 0; i < package.Errors.Count; i++) // { // message += package.Errors[i].Description; // } //} //if (!string.IsNullOrEmpty(message)) //{ // throw new Exception(message); //抛出异常 //} if (result.Equals(DTSExecResult.DTSER_SUCCESS)) return true; else return false;
}
Microsoft.SqlServer.Dts.Runtime.Wrapper.Application app = new Microsoft.SqlServer.Dts.Runtime.Wrapper.Application();
//Call the dtsx file IDTSPackage90 package = app.LoadPackage(dtsxFile, true, null); //另外还有一种方法叫LoadFromSQLServer package.Connections["File"].ConnectionString = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, csvFileName); package.Connections["本地连接"].ConnectionString = ConfigurationSettings.AppSettings["ConnStr"];
DTSExecResult result = package.Execute(); //获取包的执行信息 //string message = string.Empty; //if (result.Equals(DTSExecResult.DTSER_FAILURE)) //{ // for (int i = 0; i < package.Errors.Count; i++) // { // message += package.Errors[i].Description; // } //} //if (!string.IsNullOrEmpty(message)) //{ // throw new Exception(message); //抛出异常 //} if (result.Equals(DTSExecResult.DTSER_SUCCESS)) return true; else return false;
}
需要的配置节如下:
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
<?xml version="1.0" encoding="utf-8" ?> <configuration> <appSettings> <add key="ConnStr" value="Data Source=10.10.**.***;User ID=adminTest;Password=***;Initial Catalog=TestDb;Provider=SQLNCLI.1;Persist Security Info=True;"/> </appSettings> </configuration>