1

I am using pyodbc library to connect my Python program to a SQL Server database. I want to construct Connection String using a verbatim string as under.

connection_string =  f"DRIVER={SQL SERVER};SERVER={server};Database={database};Trusted_Connection=yes;App={app}"

Escaping { by \{ did not work.

Also making it both verbatim and raw by putting fr instead of f at the beginning of literal did not work.

Help please

Merin Nakarmi
  • 3,148
  • 3
  • 35
  • 42

1 Answers1

3

You should use {{ and }} when you need a single curly brace. From the docs:

The parts of the string outside curly braces are treated literally, except that any doubled curly braces '{{' or '}}' are replaced with the corresponding single curly brace. A single opening curly bracket '{' marks a replacement field, which starts with a Python expression.

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • If the driver is in a variable, you then need triple braces: `driver = 'whatever'; connection_string = f"DRIVER={{{driver}}} etc"` – Manngo Jun 27 '22 at 02:39