Writing to SQL Server

Saving data to SQL Server - versus Excel or some other contraption - is easy.

Assume that you have SQL Server Express installed locally. You’ve created in it a database called MYDB, and in that a table called MYTABLE. The table has ColumnA and ColumnB, which are both strings (VARCHAR) fields. And the database file is in c:\myfiles\mydb.mdf. This is all easy to set up in a GUI if you download SQL Server Express “with tools” edition. And it’s free!

  1. $cola = "Data to go into ColumnA"
  2. $colb = "Data to go into ColumnB"
  3. $connection_string = "Server=.\SQLExpress;AttachDbFilename=C:\Myfiles\mydb.mdf;Database=mydb;Trusted_Connection=Yes;"
  4. $connection = New-Object System.Data.SqlClient.SqlConnection
  5. $connection.ConnectionString = $connection_string
  6. $connection.Open()
  7. $command = New-Object System.Data.SqlClient.SqlCommand
  8. $command.Connection = $connection
  9. $sql = "INSERT INTO MYTABLE (ColumnA,ColumnB) VALUES('$cola','$colb')"
  10. $command.CommandText = $sql
  11. $command.ExecuteNonQuery()
  12. $connection.close()

You can insert lots of values by just looping through the three lines that define the SQL statement and execute it:

  1. $cola = @('Value1','Value2','Value3')
  2. $colb = @('Stuff1','Stuff2','Stuff3')
  3. $connection_string = "Server=.\SQLExpress;AttachDbFilename=C:\Myfiles\mydb.mdf;Database=mydb;Trusted_Connection=Yes;"
  4. $connection = New-Object System.Data.SqlClient.SqlConnection
  5. $connection.ConnectionString = $connection_string
  6. $connection.Open()
  7. $command = New-Object System.Data.SqlClient.SqlCommand
  8. $command.Connection = $connection
  9. for ($i=0; $i -lt 3; $i++) {
  10. $sql = "INSERT INTO MYTABLE (ColumnA,ColumnB) VALUES('$($cola[$i])','$($colb[$i])')"
  11. $command.CommandText = $sql
  12. $command.ExecuteNonQuery()
  13. }
  14. $connection.close()

It’s just as easy to run UPDATE or DELETE queries in exactly the same way. SELECT queries use ExecuteReader() instead of ExecuteNonQuery(), and return a SqlDataReader object that you can use to read column data or advance to the next row.