1

我有我的方法(除非我做了一些愚蠢的事情)昨天完美地导出到 csv。但是,今天我不断收到这个错误:

使用“1”参数调用“填充”的异常:“ExecuteReader:CommandText 属性尚未初始化”

  • $rowCount=$SqlAdapter.Fill($dt)
  • ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : NotSpecified: (:) [], MethodInvocationException
    • FullyQualifiedErrorId : InvalidOperationException

这是我的语法:

$server = "serverinstance"
$database = "databaseinstance"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "Select Top 1 * from madeuptable"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)

$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery 

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)

if ($rowCount -gt 0) { $dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation }
$connection.Close()
4

2 回答 2

0

尝试使用查询和连接创建 SqlDataAdaper(并删除 cmd)。

例子:

$SqlAdapter = new-object system.data.sqlclient.sqldataadapter ($SelectQuery, $connection)
于 2016-02-15T20:20:53.117 回答
0

我会检查你的 $server 和 $database 变量。我刚刚在我自己的 SQL 服务器上运行了你的脚本,它对我来说工作得很好。

编辑

这是我跑的:

$server = "FAR-L2484\HOLDER_SQL"  ## Hostname\InstanceID
$database = "MASTER"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "SELECT * FROM information_schema.tables"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)

$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery 

$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)

$dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation
$connection.Close()

这就是我在 C:\test\sqlresults.csv 中得到的

"TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","TABLE_TYPE"
"master","dbo","spt_fallback_db","BASE TABLE"
"master","dbo","spt_fallback_dev","BASE TABLE"
"master","dbo","spt_fallback_usg","BASE TABLE"
"master","dbo","spt_values","VIEW"
"master","dbo","spt_monitor","BASE TABLE"
"master","dbo","MSreplication_options","BASE TABLE"
于 2016-02-16T14:15:23.667 回答