SSIS Script Task - Connect ADO.NET and populate DataTable

I need to connect to SQL Server db through a script task to fill in DataTable, I use the ADO.Net provider / connection. However, for life, I get all kinds of errors. For example, when using it, SqlAdapterI get an invalid object error, however, it SqlCommandruns without errors in SSMS:

SqlConnection conn;
ConnectionManager cm;
SqlCommand cmd;

cm = Dts.Connections["AdoNet"];
conn = (SqlConnection)cm.AcquireConnection(Dts.Transaction);

using (conn)
{   
    SqlCommand cmd = new SqlCommand();
    cmd.Connection = conn;
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = queryString;
    SqlDataAdapter da = new SqlDataAdapter();
    da.SelectCommand = cmd;
    da.Fill(myDataTable);
}
+4
source share
1 answer

Try using the following code:

Using(SqlConnection conn = (SqlConnection)Dts.Connections["AdoNet"].AcquireConnection(Dts.Transaction)){

if (conn.State != ConnectionState.Open){
 conn.Open();}

SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = queryString;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(myDataTable);
}
+2
source

Source: https://habr.com/ru/post/1667218/


All Articles