5

我需要通过脚本任务连接到 SQL Server 数据库以填充DataTable,我正在使用 ADO.Net 提供程序/连接。然而,在我的一生中,我遇到了各种各样的错误。例如,当使用SqlAdapterI get an invalid object 错误时,但SqlCommand在 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

1 回答 1

3

试试下面的代码:

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);
}
于 2017-01-19T20:05:36.687 回答