Source Code and Samples

Friday 2 February 2007

Read Records from a Database

Description

This powershell script reads records from a SQL Server database and displays them on the screen.

Source Code

$connectionString = "Server=(local);Database=AdventureWorks;Integrated Security=SSPI;"
$selectStatement = "select FirstName, LastName from Person.Contact;"
$connection = new-object System.Data.SqlClient.SqlConnection($connectionString)
$connection.Open()
$command = new-object System.Data.SqlClient.SqlCommand($selectStatement, $connection)
$reader = $command.ExecuteReader()
while ($reader.Read())
{
$firstName = $reader.GetString(0)
$lastName = $reader.GetString(1)
write-output "$firstName $lastName"
}
$connection.Close()

No comments: