Home > Software design >  Test Connection pyodbc (Python and SSMS)
Test Connection pyodbc (Python and SSMS)

Time:04-20

I'm trying to follow some simple steps in this Microsoft doco but I can get it to connect.

What am I doing wrong?

import pyodbc 
# Some other example server values are
# server = 'localhost\sqlexpress' # for a named instance
# server = 'myserver,port' # to specify an alternate port
server = '029783610657\SQLEXPRESS' 
database = 'LM_Critical_Alerts' 
username = '' 
password = '' 
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' server ';DATABASE=' database ';UID=' username ';PWD='  password)
cursor = cnxn.cursor()

This is the error message:

PS C:\Users\Nelson.Silva> &

C:/Users/Nelson.Silva/AppData/Local/Programs/Python/Python310/python.exe "c:/Users/Nelson.Silva/.../Desktop/conncection test pyobdc.py"
  File "c:....conncection test pyobdc.py", line 7
    cnxn = pyodbc.connect('SERVER=' server ';DATABASE=' database ';UID=' username ';PWD='  password')
                                                                                                   ^
SyntaxError: unterminated string literal (detected at line 7)
PS C:\Users\Nelson.Silva> 

CodePudding user response:

You changed your code before posting. In the code block you say the connect line is

cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER=' server ';DATABASE=' database ';UID=' username ';PWD='  password)

but in the exception block the line is:

cnxn = pyodbc.connect('SERVER=' server ';DATABASE=' database ';UID=' username ';PWD='  password')

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)

  • Related