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)
我写了一篇关于在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相同格式的值,否则您可能会遇到错误.
运行此命令时,您将看不到控制台的任何输出.我建议事后查询以确保您的价值观被接受.
| 归档时间: |
|
| 查看次数: |
22196 次 |
| 最近记录: |