Powershell SQL Reader doesn’t work if it’s inside a function

  Kiến thức lập trình

I have been trying to separate by functions the SQL connection as well as the SQL Query.

function connect(){
    $pingResult = Test-Connection -ComputerName $serverName -Count 2 -ErrorAction SilentlyContinue
    if (-not $pingResult) {
        Write-Host "Could not reach remote machine ($serverName)."
        exit
    }
    try{
        # Create the connection
        $connection = New-Object System.Data.SqlClient.SqlConnection
        
        # Set server parameters
        $connection.ConnectionString = "Server=$serverName,$sqlPort;Database=$databaseName;Integrated Security=True;"
        
        # Open connection to SQL Server
        $connection.Open()
    
        # Return the connection for further use
        return $connection
    }
    catch {
        Write-Host "Error connecting to the database: $_"
    }

}

function Query($sqlConnection){
    try{
    
        # SqlComman object
        $command = $sqlConnection.CreateCommand()
        
        # Declare the SQL statement
        $command.CommandText = $sqlQueryAltas
    
        # Execute the query
        $command.ExecuteReader()
        # Return the object to interpret the response
        
    }
    catch {
        Write-Host "Error executing SQL statement: $_"
    }
}

$connection = connect
$reader = query($connection)
$reader.Read()

The command query($connection) returns a DataRecordInternal Object instead of a DbDataReader Object, and it results in a error because DataRecordInternal doesn’t have Read() method.

Running it all at once, just works.

# Create the connection
$connection = New-Object System.Data.SqlClient.SqlConnection

# Set the server parameters
$connection.ConnectionString = "Server=$serverName,$sqlPort;Database=$databaseName;Integrated Security=True;"

# Open the connection to the SQL server
$connection.Open()

# SqlComman object
$command = $connection.CreateCommand()

# Declare the SQL statement
$command.CommandText = $sqlQueryAltas

# Execute the read statement
$reader = $command.ExecuteReader()

# Return the object to interpret the response
$reader.Read()

New contributor

Himar Moreno Santana is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT