connect python code to SQL server Availability readonly DB failing to connect

Ashwan 536 Reputation points
2023-08-18T21:55:20.66+00:00

Hi We need to connect SQL server availability group via python code as bellow . how error not happy as facing error

import pyodbc 
print('Getting Database connection: MS SQL - AG secondary')
conn = pyodbc.connect('Driver={SQL Server};'
                              'Server=seconderyservername;'
                              'Database=DBname;'
                              'Trusted_Connection=yes;' 
                              'readonly=true;')
cursor = conn.cursor()
cursor.execute("SELECT @@servername")
row = cursor.fetchone() 
while row: 
    print(row[0])
    row = cursor.fetchone()

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The target database ('') is in an availability group and is currently access ible for connections when the application intent is set to read only

Step done:

changing server= listnername ie then connect to primary server success. looks like readonly-true doent apply correctly

changing server= Servername ie then i get following error.

checked readonly routing and its working redirect connection to secondary site:

sqlcmd    -S Listener  -d DB -K ReadOnly

any one can help please

SQL Server Other
{count} votes

1 answer

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2023-08-18T22:00:03.1466667+00:00

    The driver SQL Server is a dusty and mouldy relic from the previous millennium, and knows nothing about availability groups. You need at least SQL Server Native Client 11.0. Best is to use ODBC 18 SQL Server Driver which is the most recent ODBC driver.

    In difference to SQL Server, these drivers do not come with the OS, but you need to install them separately.

    Also readonly=true should be Application Intent=ReadOnly.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.