Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell to read from database using ODBC DSN instead of connection string

I know how to read value from database using connectionstring, i.e.

Establish database connection to read

$conn = New-Object System.Data.SqlClient.SqlConnection

$conn.ConnectionString = "Server=10.10.10.10;Initial Catalog=database_name;User Id=$username;Password=$password;"

$SQL = "..."

$conn.Open()

# Create and execute the SQL Query

$cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)

$count=0
do{
    try{
        $rdr = $cmd.ExecuteReader()



        while ($rdr.read()){
            $sql_output += ,@($rdr.GetValue(0), $rdr.GetValue(1))
            $count=$count + 1
        }
        $transactionComplete = $true

    }
    catch{
        $transactionComplete = $false
    }
}until ($transactionComplete)



# Close the database connection

$conn.Close()

How can I accomplish the same thing with ODBC, i.e I have DSN (data source name) set up on the server?

like image 400
Glowie Avatar asked Aug 14 '14 14:08

Glowie


People also ask

What is DSN in ODBC connection string?

A DSN is the saved collection of settings required to connect to an ODBC data source.


3 Answers

According to https://www.connectionstrings.com/odbc-dsn/ you would use something like...

DSN=myDsn;Uid=myUsername;Pwd=;

Can probably just go with DSN=... if creds not required.

like image 163
andyb Avatar answered Oct 20 '22 20:10

andyb


This works if your ODBC connection is under User DSN but not under System DSN. I cannot find a way to make it check for System DSN connections.

$conn = new-object System.Data.Odbc.OdbcConnection
$conn.connectionstring = "DSN=DSNNAME"
$conn.open()

$cmd = New-object System.Data.Odbc.OdbcCommand($sqlCommand,$conn)
$dataset = New-Object System.Data.DataSet
(New-Object System.Data.Odbc.OdbcDataAdapter($cmd)).Fill($dataSet) | Out- Null
$conn.Close()
like image 31
Iconiu Avatar answered Oct 20 '22 20:10

Iconiu


You may want to put this in front of the code...

If you want to do it on your local machine instead of in the context of SQL server then I would use the following. It is what we use at my company.

if ($env:Processor_Architecture -ne "x86")   
{ write-warning 'Launching x86 PowerShell'
&"$env:windir\syswow64\windowspowershell\v1.0\powershell.exe" -noninteractive -noprofile -file $myinvocation.Mycommand.path -executionpolicy bypass
exit
}

Always running in 32bit PowerShell at this point.

$env:Processor_Architecture
like image 1
Cary Avatar answered Oct 20 '22 20:10

Cary