This web site uses Kentico CMS, the content management system for ASP.NET developers.
Community > Blogs > Max-PIT> SQL-Server and PowerShell > December 2008 > Read/Display Data from SQL Server
 

Read/Display Data from SQL Server

Part 3 of 3

Now, here's the sample code were you can connect and data from a SQL server.  Using the same connection type from the previous samples.  Now, we can run a SQL Query using the 'Select ...from..." and load the data into our PowerShell variable.  We accomplished this task using the SqlClient.SqlDataAdapter class.  Let's chek it out:

Read/Display Data from SQL table

## - Defining your SQL Server Parameters
$SqlServer = "YourSQLServerName";
$SqlDatabase = "YourDatabaseName";

## - Building the SQL connection string
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SqlServer; Database = $SqlDatabase; " `
+ "Integrated Security = True; Connect TimeOut=300";

## - Open connection to SQL Server
$SqlConnection.Open()

## - Define your SQL statement
$SqlQuery = "Select LastName, FirstName, City, State from tblPerson";

## - Section to SQLQuery
$SqlCmd.CommandText = $SqlQuery;
$SqlCmd.Connection = $SqlConnection;
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter;
$SqlAdapter.SelectCommand = $SqlCmd;

## - Building the Dataset collection objects that will store the results of the query
$DataSet = New-Object System.Data.DataSet;
$SqlAdapter.Fill($DataSet);

## - Close connection to SQL Server
$SqlConnection.Close();

## - Pipe the Dataset collection and display the records on screen
$DataSet.Tables[0] | Select LastName, FirstName, City, State | FT -autosize ;

## - End of Script


Please, to test this script you need to build a table to similate the sample.  But this code will work,  So at the end you will be able to list the records from the table.  The rest you could use your imagination.

This is the end of the 3 part shortcut series,

Posted: 12/13/2008 7:38:52 PM by Global Administrator | with 1 comments


Comments
irxwszkfy
7bpKYV drjvbwvjgrgy, [url=http://boyzuinsyqog.com/]boyzuinsyqog[/url], [link=http://tnjyckhexahx.com/]tnjyckhexahx[/link], http://kjqwjbobikpy.com/
4/5/2009 5:47:03 PM

Title

In this blog section I will provide some valid samples currently use at my workplace.  I'll be covering SQL Server version: 2000, 2005, and 2008.  Also, I will post some information on SQLPS.exe.

Take a look at the three part series on:
1. Connecting to SQL Server
2. Executing a SQL Command (using "Delete from...")
3. Read/Display Data from SQL Server

l be posting more thing in the near future such as using SMO and doing some SQL admin operations.  

 

Syndication

RSS
This web site uses Kentico CMS, the content management system for ASP.NET developers.