As an alternative to ExecuteReader below, it is also possible to run insert/update statements using the ExecuteNonQuery method because they do not return rowsets that need to be fetched and processed.
# Mike Burr
# March 2013
# Demonstration Script to perform basic Microsoft SQL Server query using PowerShell
[System.Reflection.Assembly]::LoadWithPartialName("System.Data.SqlClient")
# Define the connection string for the database connection. Typically the
# account running the script or the application pool identity
# has appropriate access to the database allowing integrated security
# to be used. In limited cases, it may be necessary to define a username and
# password in the connection string
$ConnectionString = "Data Source=localhost;Database=MyTestDB;Integrated Security=True;"
$conn = new-object "System.Data.SqlClient.SqlConnection" $ConnectionString
Try {
$conn.Open()
$cmd = $conn.CreateCommand()
$cmd.CommandText = "SELECT DISTINCT a FROM Test where a = @a"
$reader = $cmd.ExecuteReader()
while ($reader.Read()) {
$value = $reader["a"]
}
} Finally {
$conn.Close();
} -->See Also:
How to Query a MySql Database using Windows PowerShell
Hello Mike!
ReplyDeleteVery good blog! You have some very informative posts and lots of great advice and tips for developers but also bigger variety of posts. I think I could help to get you some new readers if you are interested?
I am looking for quality blogs to include into our community of bloggers - glipho.com
Please check us out and drop me a line at hubert@glipho.com for any questions.
Best!
Hubert