C# 在 SSIS 中的脚本任务中连接到 SQL 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11867639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:34:47  来源:igfitidea点击:

Connect to SQL database inside Script Task in SSIS

c#sqlsql-serverssisscript-task

提问by NealR

Inside of a Script Task in SSIS, I need to make a call to an SQL database. I have a connection string that was created when I added the database to the data sources folder, however now I'm not sure how to reference it inside the C# code. I know how to do this in the code behind of an ASP website, however it seems that SSIS should have a more direct method.

在 SSIS 中的脚本任务内部,我需要调用 SQL 数据库。我有一个在将数据库添加到数据源文件夹时创建的连接字符串,但是现在我不确定如何在 C# 代码中引用它。我知道如何在 ASP 网站背后的代码中执行此操作,但是似乎 SSIS 应该有更直接的方法。

EDIT

编辑

This line of code actually winds up throwing an exception:

这行代码实际上最终抛出了一个异常:

sqlConn = (System.Data.SqlClient.SqlConnection)cm.AcquireConnection(Dts.Transaction);

It reads: "Unable to cast COM object of type 'System._ComObject' to class type 'System.Data.SqlClient.SqlConection.'"

它显示:“无法将类型为‘System._ComObject’的 COM 对象转换为类类型‘System.Data.SqlClient.SqlConection’。”

采纳答案by Diego

you cant use the configurations from a connection manager from inside a script task like: conectionManager1.exceuteSQLStatment(...)

您不能在脚本任务中使用来自连接管理器的配置,例如:conectionManager1.exceuteSQLStatment(...)

once you are "inside" the script task you need to access the CM like a variable:

一旦你“在”脚本任务中,你需要像变量一样访问 CM:

ConnectionManager cm;
System.Data.SqlClient.SqlConnection sqlConn;
System.Data.SqlClient.SqlCommand sqlComm;

cm = Dts.Connections["conectionManager1"];

sqlConn = (System.Data.SqlClient.SqlConnection)cm.AcquireConnection(Dts.Transaction);
sqlComm = new System.Data.SqlClient.SqlCommand("your SQL Command", sqlConn);
sqlComm.ExecuteNonQuery();

cm.ReleaseConnection(sqlConn);

回答by Hugo Vares

You must check the privider of the connection that your are trying to instantiate.

您必须检查您尝试实例化的连接的特权。

You can't cast a OleDb.OleDbConnectionconnection as a SQLClient.SQLConnection, the parameters are different.

您不能将OleDb.OleDbConnection连接转换为 a SQLClient.SQLConnection,参数不同。