I’m trying to follow some simple steps in this Microsoft doco but I can get it to connect.
What am I doing wrong?
JavaScript
x
11
11
1
import pyodbc
2
# Some other example server values are
3
# server = 'localhostsqlexpress' # for a named instance
4
# server = 'myserver,port' # to specify an alternate port
5
server = '029783610657SQLEXPRESS'
6
database = 'LM_Critical_Alerts'
7
username = ''
8
password = ''
9
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
10
cursor = cnxn.cursor()
11
This is the error message:
PS C:UsersNelson.Silva> &
JavaScript
1
7
1
C:/Users/Nelson.Silva/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/Nelson.Silva/.../Desktop/conncection test pyobdc.py"
2
File "c:....conncection test pyobdc.py", line 7
3
cnxn = pyodbc.connect('SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password')
4
^
5
SyntaxError: unterminated string literal (detected at line 7)
6
PS C:UsersNelson.Silva>
7
Advertisement
Answer
You changed your code before posting. In the code block you say the connect line is
JavaScript
1
2
1
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
2
but in the exception block the line is:
JavaScript
1
2
1
cnxn = pyodbc.connect('SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password')
2
The problem is not the connection. Your python code is invalid. Python is telling you that you haven’t closed one of your strings: SyntaxError: unterminated string literal (detected at line 7)
It also gives you a convenient little ^
under where it thinks you haven’t closed a string. In the exception block its at the end of the ;PWD='+ password')
.
';PWD='+ password')
should be ';PWD='+ password)
(notice the lack of ‘ at the end of password
)