In our projects, we sometimes need to fetch the data from Oracle database and use it in our projects.

We will see a very simple executable script which will allow us to connect to the database very quickly and efficiently, and store it in a data set so that we don’t have to connect the database every time to get the data, as that will make the script really slow if you have thousands of data.

Let’s see how can we do it.

Steps

  1. Open Windows PowerShell Modules as an Administrator.



  2. Paste the following code as .ps1 file and execute it.

Code

  1. #Add the PowerShell snap in code
  2. Add-PSSnapIn Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue | Out-Null
  3. #Oracle Database Connection
  4. #Load the assembly file (Oracle.DataAccess.dll) from the server you are running the script from
  5. $AssemblyFile = “C:\oracle\product\11.2.0\client_1\ODP.NET\bin\2.x\Oracle.DataAccess.dll"
  6. #Connection to the Oracle Database
  7. $ConnectionString = "Data Source=Provide your source:Provide your port number / Provide your source name;User Id=Your User ID;Password=Your Password;Persist Security Info=True"
  8. #Select the columns you want from the Oracle Database
  9. $CommandText = "SELECT Emp FROM EmpDB"
  10. #Initiate the process
  11. [Reflection.Assembly]::LoadFile($AssemblyFile) | Out-Null
  12. $OracleConnection = New-Object -TypeName Oracle.DataAccess.Client.OracleConnection
  13. $OracleConnection.ConnectionString = $ConnectionString
  14. $OracleConnection.Open()
  15. #Your Database is connected
  16. Write-Host "Oracle Database Connected"
  17. #Load the Oracle Data in a Dataset
  18. $OracleCommand = New-Object -TypeName Oracle.DataAccess.Client.OracleCommand
  19. $OracleCommand.CommandText = $CommandText
  20. $OracleCommand.Connection = $OracleConnection
  21. #Use the Oracle Data Adapter
  22. $OracleDataAdapter = New-Object -TypeName Oracle.DataAccess.Client.OracleDataAdapter
  23. $OracleDataAdapter.SelectCommand = $OracleCommand
  24. #Create a new Data set
  25. $DataSet = New-Object -TypeName System.Data.DataSet
  26. $OracleDataAdapter.Fill($DataSet) | Out-Null
  27. #Dispose the connection
  28. $OracleDataAdapter.Dispose()
  29. $OracleCommand.Dispose()
  30. $OracleConnection.Close()
  31. $data= $DataSet.Tables[0]
  32. #You will have all the data without being connected stored in the dataset
  33. Write-Host $DataSet.Tables[0].Rows.Count

Prerequisites

The above parameters are required from your end while connecting to the database. Once you get the correct parameters and execute the script, you will get a message “Oracle Database Connected”.

This data set will help you to have the complete Oracle data offline, therefore you don’t have to read the database over time, hence, saving your instance and time duration on it.

Here, in this article, we saw how to get Oracle Database content on a data set, using PowerShell Script.

Keep reading & keep learning!