1 | initial version |
To execute SQL transactions using PowerShell, you can follow the steps below:
Install-Module -Name SqlServer
New-SqlConnection
cmdlet. For example:$connectionString = "Server=<serverName>;Database=<databaseName>;Integrated Security=True"
$connection = New-SqlConnection -ConnectionString $connectionString
Open()
method of the connection object. For example:$connection.Open()
New-SqlCommand
cmdlet. For example:$command = New-SqlCommand -Query "SELECT * FROM <tableName>" -Connection $connection
ExecuteReader()
method. For example:$reader = $command.ExecuteReader()
Read()
method of the reader object. For example:while($reader.Read())
{
# Process each row
}
Close()
method. For example:$reader.Close()
$connection.Close()
ExecuteNonQuery()
method of the SqlCommand
object. For example:$command = New-SqlCommand -Query "INSERT INTO <tableName> VALUES (<value1>, <value2>, ...)" -Connection $connection
$command.ExecuteNonQuery()
Note: It is recommended to use parameterized queries to prevent SQL injection attacks.