如何使用PowerShell从SQL Server中的.csv导入数据?

Art*_*ka1 3 sql-server powershell

我有以下场景:我使用PowerShell并且必须将.csv文件中的数据导入到SQL Server数据库上已创建的表中.所以我不需要csv的标题行,只需写入数据.

这是我到目前为止所做的:

#Setup for SQL Server connection
#SQL Server Name
$SQLServer = "APPLIK02\SQLEXPRESS"
#Database Name
$SQLDBName = "code-test"

#Create the SQL Connection Object
$SQLConn = New-Object System.Data.SQLClient.SQLConnection
#Create the SQL Command Object, to work with the Database
$SQLCmd = New-Object System.Data.SQLClient.SQLCommand

#Set the connection string one the SQL Connection Object
$SQLConn.ConnectionString = "Server=$SQLServer;Database=$SQLDBName; Integrated Security=SSPI"
#Open the connection
$SQLConn.Open()

#Handle the query with SQLCommand Object
$SQLCmd.CommandText = $query
#Provide the open connection to the Command Object as a property
$SQLCmd.Connection = $SQLConn

#Execute 
$SQLReturn=$SQLCmd.ExecuteReader()

Import-module sqlps
$tablename = "dbo."+$name

Import-CSV .\$csvFile | ForEach-Object Invoke-Sqlcmd 
  -Database $SQLDBName -ServerInstance $SQLServer 
  #-Query "insert into $tablename VALUES ('$_.Column1','$_.Column2')"
#Close
$SQLReturn.Close()  
$SQLConn.Close()
Run Code Online (Sandbox Code Playgroud)

Fox*_*loy 8

我写了一篇关于在PowerShell中使用SQL的博客文章,所以你可以在这里阅读更多相关信息.

如果您有SQL-PS模块,我们可以轻松完成此操作.只需提供数据库名称,服务器名称和表的值,然后运行以下命令:

$database = 'foxdeploy'
$server = '.'
$table = 'dbo.powershell_test'

Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd `
  -Database $database -ServerInstance $server `
  -Query "insert into $table VALUES ('$($_.Column1)','$($_.Column2)')"
  }
Run Code Online (Sandbox Code Playgroud)

为清楚起见,将Column1,Column2替换为CSV中列的名称.

请确保您的CSV具有与SQL DB相同格式的值,否则您可能会遇到错误.

运行此命令时,您将看不到控制台的任何输出.我建议事后查询以确保您的价值观被接受.

  • 如果不将每个`$ _。colname`放入子表达式(`$($ _。colname)`),则可能无法工作。请解决此问题。另外,请注意,将变量放在这样的SQL语句中会使您容易受到[SQL注入](https://en.wikipedia.org/wiki/SQL_injection)的攻击。您可能需要考虑使用[prepared statement](http://stackoverflow.com/a/43308134/1630171)。 (4认同)