Created
October 17, 2013 19:01
-
-
Save codecontemplator/7030351 to your computer and use it in GitHub Desktop.
powershell database connection utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.DESCRIPTION | |
Create a database connection and add extension methods (script methods) that can load and | |
save a System.Data.Dataset | |
.PARAMETER ConnectionString | |
Connection string to database. | |
.EXAMPLE | |
Open connection, load data, update and create new records. | |
$conn = Get-DatabaseConnection "Data Source=localhost; Initial Catalog=MyDatabase; Integrated security=true" | |
$ds = $conn.GetDataSet("select Id, Name from Users") | |
$dt = $ds.Tables[0] | |
$dt.Rows[0].Name = "New name" | |
$newUser = $dt.NewRow() | |
$newUser.Name = "Daniel" | |
$dt.Rows.Add($newUser) | |
$conn.SaveDataSet($ds) | |
$conn.Close() | |
#> | |
function Get-DatabaseConnection($ConnectionString) | |
{ | |
$connection = New-Object System.Data.SqlClient.SqlConnection $connectionString | |
$connection.Open() | |
$connection | Add-Member ScriptMethod GetDataSet { | |
param([string]$sql) | |
$dataset = New-Object System.Data.Dataset | |
$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $sql, $this | |
$dataAdapter.Fill($dataset) | out-null | |
$dataset.ExtendedProperties["sql"]= $sql | |
$dataset | |
} | |
$connection | Add-Member ScriptMethod SaveDataSet { | |
param([System.Data.DataSet]$dataset) | |
$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $dataset.ExtendedProperties["sql"], $this | |
$commandBuilder = New-Object System.Data.SqlClient.SqlCommandBuilder $dataAdapter | |
$dataAdapter.UpdateCommand = $commandBuilder.GetUpdateCommand() | |
$dataAdapter.InsertCommand = $commandBuilder.GetInsertCommand() | |
$dataAdapter.DeleteCommand = $commandBuilder.GetDeleteCommand() | |
$dataAdapter.Update($dataset) | |
} | |
$connection | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment