I am trying to connect to the SQL server in python using pyodbc. I am unable to connect because my database is ReadOnly. I tried the solutions provided at other link:
import pyodbc readonly_conn_str = "DRIVER={SQL Server};SERVER=...; DATABASE=...;readonly=True;" conn = pyodbc.connect(readonly_conn_str)
But, I am still getting the following error:
ProgrammingError: (‘42000’, “[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The target database (‘PRMOperationalDB’) is in an availability group and is currently accessible for connections when the application intent is set to read only. For more information about application intent, see SQL Server Books Online. (978) (SQLDriverConnect); [42000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0); [42000] [Microsoft][ODBC SQL Server Driver][SQL Server]The target database (‘PRMOperationalDB’) is in an availability group and is currently accessible for connections when the application intent is set to read only. For more information about application intent, see SQL Server Books Online. (978); [42000] [Microsoft][ODBC SQL Server Driver]Invalid connection string attribute (0)”)
Any suggestions how to resolve this issue?
Advertisement
Answer
readonly=True
is an attribute of pyodbc’s connect()
method, not a part of the connection string you pass to SQL Server. IMHO try just passing all the attributes instead of building a full connection string:
conn = pyodbc.connect(driver='{SQL Server}', host=<server>, database=<db>, trusted_connection='yes', user='', password='', readonly = True)
Or, like the answer you mentioned offered, use:
conn = pyodbc.connect('driver={ODBC Driver 17 for SQL Server};' + 'SERVER=...;DATABASE=...;' + 'UID=' + user + ';PWD=' + password + ';' + 'ApplicationIntent=ReadOnly')
Also, are you intentionally connecting explicitly to a secondary? Why don’t you connect to the AG name and if your app is doing only read operations then the worst that happens (if, say, someone breaks read-only routing) is that those read operations happen on the primary. Your code should never connect to a specific physical host / cluster node and assume that will always be a read-only secondary… what happens if there is a failover tomorrow? Who’s updating all the connection strings?